Parsing command-line arguments in C?

后端 未结 12 844
眼角桃花
眼角桃花 2020-11-22 16:23

I\'m trying to write a program that can compare two files line by line, word by word, or character by character in C. It has to be able to read in command line options

12条回答
  •  猫巷女王i
    2020-11-22 16:47

    #include 
    
    int main(int argc, char **argv)
    {
        size_t i;
        size_t filename_i = -1;
    
        for (i = 0; i < argc; i++)
        {
            char const *option =  argv[i];
            if (option[0] == '-')
            {
                printf("I am a flagged option");
                switch (option[1])
                {
                    case 'a':
                        /*someting*/
                        break;
                    case 'b':
                        break;
                    case '-':
                        /* "--" -- the next argument will be a file.*/
                        filename_i = i;
                        i = i + 1;
                        break;
                    default:
                        printf("flag not recognised %s", option);
                        break;
                }
            }
            else
            {   
                printf("I am a positional argument");
            }
    
            /* At this point, if -- was specified, then filename_i contains the index
             into argv that contains the filename. If -- was not specified, then filename_i will be -1*/
         }
      return 0;
    }
    

提交回复
热议问题