【发布时间】: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