我正在尝试从一个函数 process_command_line
解析命令行参数,然后我将在 main
函数中使用该参数。第二个命令行参数允许提交要提交的文件输入的名称,该名称稍后将用于读/写文件。目前,我将只打印 main
函数中的参数,以确保它正常运行。我使用这个单独的函数方法解析整数没有问题,但在尝试解析输入
文件名时无法获得正确的输出。
编辑:我认为我的问题在于第二个函数,其中有一行表示 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
}
最佳答案
在用户对这个问题的帮助下,这是我更新且有效的解决方案。问题是我没有在 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]);
}
关于c - 如何从单独的函数解析命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680711/