c - 如何从单独的函数中解析命令行参数
问题描述
我试图从一个函数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
}
解决方案
在用户对这个问题的帮助下,这是我更新且功能正常的解决方案。问题是我没有在我的函数中调用第二个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]);
}
推荐阅读
- sql - SQL 表结构 - 经销商定价
- html - 签入 Microsoft Edge 时下拉菜单出现问题
- java - SceneBuilder - 添加依赖于第三方组件的自定义组件
- c - 全局和局部范围变量(为什么第二个打印输出 28 在这里?)
- javascript - 在 React 中获取和更新数据的最佳方法
- javascript - 如何通过单击 var phraseArray 句子上的按钮来添加 css 或 javascript 可重复的打字机效果?
- .net-core - 当 EFCore 尝试将数据从存储库返回到控制器时,为什么 asp.net 核心项目会崩溃?
- go - 浏览器显示先前的响应
- r - 用出现的下一个数字替换 NA
- html - SVG inside HTML table behavior with box-sizing and borders