纯C语言下如何通过命令行向被驱动的次级程序传递参数?
驱动程序调用次级程序的参数传递问题解决
问题根源
你遇到的usage错误有两个核心原因:
- 调用对象错误:你用
system("C:/myProg/main.c")直接运行了C源文件,这是无效的——必须运行编译后的可执行文件(比如main.exe)。 - 参数未传递:驱动程序完全没把用户传入的文件参数传给次级程序,导致次级程序启动时
argc=1,触发了usage分支。
关于参数传递方式的选择
两种方式都能实现,但更合理的是由驱动程序在调用时传递文件参数:
- 驱动程序作为入口层,负责接收用户的命令行输入,再将必要的参数转发给次级程序,符合分层设计的逻辑。
- 如果让次级程序直接读取命令行参数,用户需要同时满足驱动和次级程序的参数格式,灵活性极差,失去了驱动程序作为中间层的意义。
修改后的代码示例
驱动程序 driver.c
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { int arg_count; for (arg_count = 0; arg_count < argc; arg_count++) { printf("argv[%2d]: %s\n", arg_count, argv[arg_count]); if (arg_count == 1) { if (strcmp(argv[1], "-p") == 0) { // 检查是否传入了文件参数 if (argc < 3) { fprintf(stderr, "错误:请指定要读取的文件路径\n"); exit(1); } // 拼接命令字符串,传递文件参数给次级程序 char cmd[256]; snprintf(cmd, sizeof(cmd), "C:/myProg/main.exe %s", argv[2]); system(cmd); } } } return 0; }
次级程序 main.c(补充缺失的usage函数)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> // 补充缺失的usage函数实现 void usage(const char *prog_name) { fprintf(stderr, "用法:%s <文件路径>\n", prog_name); exit(1); } int main(int argc, char *argv[]) { FILE *process_in_file; int ch; if (argc == 1) { usage(argv[0]); } if ((process_in_file = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "无法打开文件 %s: %s\n", argv[1], strerror(errno)); exit(1); } while ((ch = fgetc(process_in_file)) != EOF) { printf("%c", ch); } fclose(process_in_file); exit(0); }
关键修改说明
- 调用可执行文件:将
system中的main.c改为编译后的main.exe(确保次级程序已完成编译)。 - 参数拼接:用
snprintf拼接包含文件参数的命令字符串,确保次级程序能收到文件路径参数。 - 参数校验:驱动程序中增加参数数量检查,避免用户只输入
-p却不指定文件的情况。
内容的提问来源于stack exchange,提问作者raven_lee
相关产品推荐
相关产品推荐

