简体   繁体   中英

How can I add options to argument in c/c++ ? ( visual studio Platform 2019 )

I want to add Options to arguments in c/c++. Visual studio console application.

for example:

-f [ File path ] -e [ "exe" file ] etc..

thanks ;).

Here is a simple program that parses the input arguments based on the -f and -e flags. The error handling for the invalid arguments must be improved and implemented in such a way that matches your specific application.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

typedef struct arguments {
    char *fname;
    int file_flag;
    char *exename;
    int exe_flag;
} arguments;

int main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind;

    int c = 0;
    arguments *input_args;

    input_args = (arguments *)malloc(sizeof(arguments));
    if (input_args == NULL) {
        fprintf(stderr, "Failed to allocate memory!\n");
        return -1;
    }
    input_args->file_flag = 0;
    input_args->exe_flag = 0;

    /* You can initialize the  arguments with some default values */
    input_args->exename =  "default_exename";
    input_args->fname =  "default_filename";

    const char *usage = "Usage: %s -f [File path] -e [exe file]\n";

    while ((c = getopt(argc, argv, "f:e:")) != -1)
        switch (c) {
        case 'f':
            input_args->file_flag = 1;
            input_args->fname = optarg;
            break;
        case 'e':
            input_args->exe_flag = 1;
            input_args->exename = optarg;
            break;
        default:
            fprintf(stderr, usage, argv[0]);
            return -1;
    }

    if (0 == input_args->file_flag)
    {
        printf("No file argument provided!\n");
        printf("Initializing the file name with default value %s!\n", input_args->fname);
    }

    if (0 == input_args->exe_flag) {
        printf("No exe argument provided!\n");
        printf("Initializing the exe name with default value %s!\n\n", input_args->exename);
    }

    printf("File name = \"%s\"\n", input_args->fname);
    printf("Exe name = \"%s\"\n", input_args->exename);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM