سؤال

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