Search code examples
cfopengetopt

Problem with fopen error using getopt optarg


Running it does not open the file that i'm parsing with optarg in option -w.

I run with ./programname -w filename.txt

filename.txt is in the same directory with exe file etc...

I post here a part of code to let you understand, thank you!

P.S. Sorry for my bad english!

    while((opt = getopt(argc, argv, "lw")) != -1) 
        switch(opt) {
            case 'l': {
                //... do something ...
            } break;

            case 'w': {
                int counter = 0;
                FILE* ifp = fopen(optarg, "r"); 
                CHECK_OPEN_FILE(ifp, optarg);
                while(fgets(buffer, 256, ifp) != NULL)
                    counter += wordscounter(buffer);
                fprintf(stdout, "File has %d words.\n", counter);
                fclose(ifp);
            }break;

            case '?': {
                if(optopt == '-')
                    break;
                fprintf(stderr, "ERROR: Option -%c unrecognized...\n", optopt);
            } break;

        }

In this part of code i have a problem:

FILE* ifp = fopen(optarg, "r"); 
CHECK_OPEN_FILE(ifp, optarg);

Solution

  • If such a character is followed by a colon, the option requires an argument

    You are missing : for option w. You should have lw: specifying that w has a value. Else optarg is null

    The man page