c - C 中的 fgets 函数和文件处理

标签 c

我正在尝试制作一个程序,它将用户输入的数据存储在一个文本文件中,该文件的名称由用户提供。当用户输入 exit 时,程序将终止。 string.h的strcmp函数用于字符串比较,fgets()用于从stdin读取数据。

这是我的代码。

#include<stdio.h>
#include<string.h>

void main()
{
    char file[60];          // will store file name
    printf("Enter file name: ");
    fgets(file, 59, stdin);

    FILE *fp = fopen(file, "a+");   // open file in append mode

    if(fp == NULL){
        printf("File not found !");
        return;
    }

    char data[100];
    printf("Enter some data to add to file(exit to terminate): ");
    fgets(data, 99, stdin);

    int flag = strcmp(data, "exit");

    while(flag != 0){
        fputs(data, fp);

        fgets(data, 59, stdin);
        flag = strcmp(data, "exit");
        printf("%d\n", flag);       // for checking whether string are correctly comapred or not
    }

    printf("Bye");

}

即使我输入 exit,程序也不会终止。我还尝试在用户输入的字符串末尾连接“\n”,但这也无济于事。虽然 gets() 函数工作正常,但我知道它不是我转向 fgets() 的首选,但它对我不起作用。

最佳答案

检查 man page对于 fgets(),它读取并存储输入后的换行符(由按 ENTER 引起)。因此,strcmp() 失败。

在比较输入之前,您必须手动从换行符中删除输入缓冲区。一种简单而优雅的方法是

 data[strcspn(data, "\n")] = 0;

关于c - C 中的 fgets 函数和文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209676/

相关文章:

c++ - 使用设备文件符号链接(symbolic link)查找总线号和设备号

c++ - WINAPI URLDownloadToFileA 问题

c++ - 如何在 Windows 中锁定文件?

c - 你如何检查一个目录是否存在于 C 的 Windows 上?

c - 将 C 程序翻译成 IA32 程序集(非常快)

c - 如何在汇编中正确调用函数

c - Net-SNMP 自定义 MIB 处理程序

c - C 矩阵的转置(行主序)

c - 如何捕获特定linux系统的返回

c - 为什么相同的输入(0)我的输出会增加?