首页 > 解决方案 > 如何从单独的函数中解析命令行参数

问题描述

我试图从一个函数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

}

标签: cparsingcommand-lineparameter-passingcommand-line-arguments

解决方案


在用户对这个问题的帮助下,这是我更新且功能正常的解决方案。问题是我没有在我的函数中调用第二个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]);

}

推荐阅读