c - 如何从单独的函数解析命令行参数

标签 c parsing command-line parameter-passing command-line-arguments

我正在尝试从一个函数 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/

相关文章:

c - UEFI 编程 : How to Initialize a CHAR16 Unicode String?

linux - 解析和替换两个文件中的一些字符串

json - 处理 json 数据时出错 : The data couldn’t be read because it isn’t in the correct format

command-line - QuickTime 使用 FFMPEG 对可读电影进行编码

windows - 在 Windows 中从命令行编译 Qt 应用程序

c - POSIX 中的 fopen 与 open(C 语言)

c - Logitech网络摄像头USB C Windows

c - 在 yacc 和 lex char 数组中制作计算器

parsing - 在 golang 中解析 NeDB 文件

awk - 使用 Bash 从每个基因的 fasta 序列中提取位置 2-7