C 程序 strcmp 不工作

标签 c linux unix strcmp

我对为什么输入没有正确地与“历史记录”进行比较感到困惑。无论我输入什么,它似乎都不会进入 if 语句。一旦我输入 history 它就应该进入 if 语句。我尝试使用 scanf("%s\n", input);还可以看到它工作正常,但不是我想要的方式。

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); 
        }
    }
}

最佳答案

当您键入“history\n”时,fgets() 会读取并存储换行符。尝试在您的 if 语句中使用 strncmp(input, "history", 7) 或 "strcmp(input, "history\n")。

关于C 程序 strcmp 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452350/

相关文章:

c - 如何将字符串转换为 double 浮点值?

database - 验证文件完整性?

linux - 默认情况下,剪切命令未正确提取字段

c - 找到数字乘积为 N 的最小数字 Q

c - 为没有 .so 文件的共享库构建

c - 如何将 C 结构体与 4 字节边界对齐?

android - 在 Android 上查找 SD 卡卷标

linux - 如何识别长时间运行的进程是否死亡?

c++ - <'variable/function'的多重定义 >

c - AIX,子进程退出时父进程无法捕获 SIGCHLD