【问题标题】:How to parse command-line arguments from a separate function如何从单独的函数中解析命令行参数
【发布时间】:2019-09-04 22:27:14
【问题描述】:

我正在尝试从一个函数process_command_line 解析命令行参数,然后我将在main 函数中使用它。第二个命令行参数允许提交文件输入的名称,稍后将用于读取/写入文件。暂时,我将只打印出main 函数中的参数,以确保它正常运行。使用这种单独的函数方法解析整数没有问题,但在尝试解析 input 文件名时无法获得正确的输出。

编辑:我认为我的问题在于第二个函数,我有一行说argv[1] = input_file;

我的尝试:

#include <stdio.h>
#include <stdlib.h>

int process_command_line(int argc, char *argv[]);   //declaration for command-line function

char str2[100];

int main(int argc, char *argv[]) {

    printf("%s", str2);
    getchar();
    return 0; 
}

//This function reads in the arguments 
int process_command_line(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Error: Missing program arguments.\n");
        exit(1);
    }

    //first argument is always the executable name (argv[0])

    //second argument reads in the input file name 
    strcpy(str2, argv[1]); //I think this is where the problem lies

}

【问题讨论】:

  • 你意识到你需要将参数传递给第二个函数并调用它,对吧?
  • 你在哪里有argv[1] = input_file; 你打算strcpy(input_file, argv[1]); 吗?如果是这样,您需要采取措施确保input_file[] 不会溢出。
  • @DavidHoelzer 我不确定我理解你的意思——你能详细说明一下吗?
  • 你在哪里给process_command_line()打电话?
  • 你需要在main中调用那个函数,否则你认为它什么时候执行?在printf 之前添加process_command_line(argc,argv);(在%s 之后添加\n,顺便说一句)。

标签: c parsing command-line parameter-passing command-line-arguments


【解决方案1】:

在用户对这个问题的帮助下,这是我的更新和有效的解决方案。问题是我没有在main 函数中调用第二个函数。

我的解决方案:

#include <stdio.h>
#include <stdlib.h>

int process_command_line(int argc, char *argv[]);   //declaration for command-line function

char str2[100];

int main(int argc, char *argv[]) {

    process_command_line(argc, argv); //This was missing in my first attempt
    printf("%s", str2);
    getchar(); 
    return 0; 
}

//This function reads in the arguments 
int process_command_line(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Error: Missing program arguments.\n");
        exit(1);
    }

    //first argument is always the executable name (argv[0])

    //second argument reads in the input file name  
    strcpy(str2, argv[1]);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 2013-03-21
    相关资源
    最近更新 更多