문제

I'm a little confused on why the input isn't comparing with the "history" correctly. It seems to never go into the if statement no matter what I type. Once I type history it's suppose to go into the if statement. I tried using scanf("%s\n", input); also to see and that works correctly but not the way I want it to.

while(fgets(input, sizeof(input), stdin) != NULL){

    filePrint = fopen(".simpleshell_history", "a");
    fileRead = fopen(".simpleshell_history", "r");      

    count++;
    fprintf(filePrint, "%d - %s", count, input);
    fclose(filePrint);

    if (strcmp(input,"history")==0){
        printf("%s\n", input);
        fseek(fileRead, 0, SEEK_SET);
        int x = 0;
        while ((x = fgetc(fileRead)) != EOF){
            printf("%c", x); 
        }
    }
}
도움이 되었습니까?

해결책

When you type "history\n", fgets() reads and stores the newline. Try using either strncmp(input, "history", 7) or "strcmp(input, "history\n") in your if statement.

다른 팁

fgets doesn't trim the new-line character from input. You'll need to do this yourself before using strcmp.

You can trim it by doing something like this:

input[strlen(input) - 1] = '\0';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top