[英]How to parse command-line arguments from a separate function
我正在嘗試從一個函數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]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.