Parsing command-line arguments in C?

后端 未结 12 702
眼角桃花
眼角桃花 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条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 16:46

    Instructional template for parsing command line arguments in C.

    C:>programName -w -- fileOne.txt fileTwo.txt

    BOOL argLine = FALSE;
    BOOL argWord = FALSE;
    BOOL argChar = FALSE;
    char * fileName1 = NULL;
    char * fileName2 = NULL;
    
    int main(int argc, char * argv[]) {
        int i;
        printf("Argument count=%d\n",argc);
        for (i = 0; i < argc; i++) {
            printf("Argument %s\n",argv[i]);
            if (strcmp(argv[i],"-l")==0) {
                argLine = TRUE;
                printf("    argLine=TRUE\n");
            }
            else if (strcmp(argv[i],"-w")==0) {
                argWord = TRUE;
                printf("    argWord=TRUE\n");
            }
            else if (strcmp(argv[i],"-c")==0) {
                argChar = TRUE;
                printf("    argChar=TRUE\n");
            }
            else if (strcmp(argv[i],"--")==0) {
                if (i+1 <= argc) {
                    fileName1 = argv[++i];
                    printf("    fileName1=%s\n",fileName1);
                }
                if (i+1 <= argc) {
                    fileName2 = argv[++i];
                    printf("    fileName2=%s\n",fileName2);
                }
            }
        }
        return 0;
    }
    

提交回复
热议问题