【问题标题】:Repetition of the last string when reading from .txt file C从 .txt 文件 C 读取时重复最后一个字符串
【发布时间】:2018-07-15 15:14:01
【问题描述】:

这是代码,它从文件中读取,然后打印该文件中写入的内容。 我不知道为什么,但是文件的最后一个字符串被读取了两次。

代码

FILE* src = fopen(name_email_src, "r");
if (src == NULL)
{
    printf("ERROR source file not found");
}
while(fgets(buff_src, sizeof(buff_src), src) != NULL)
{
    fputs(buff_src, stdout);
}
fclose(src);
printf("%s", buff_src);

这是输出:

Date: Tue, 07 Feb 2017 21:32:46 +0100 (CET)
From: Rental <rental@house-rental.com>
To: me <me@upf.edu>
Message-ID: message2
Subject: Paga el alquiler ya.

Dear customer,

you are late in your payment, please pay or LEAVE!

Sincerely yours,
House rental
House rental

我能做些什么来解决这个问题?谢谢。

【问题讨论】:

  • 使用调试器单步调试程序会很快告诉你问题出在哪里。
  • 为什么代码中包含printf("%s", buff_src);

标签: c


【解决方案1】:

printf("%s", buff_src); 正在打印最后一行。

【讨论】:

    【解决方案2】:

    在您的while 循环之后,您需要额外调用printf()

    while(fgets(buff_src, sizeof(buff_src), src) != NULL)
    {
        fputs(buff_src, stdout); // prints each line
    }
    fclose(src);
    printf("%s", buff_src); // prints buff_src which still holds the last line
    

    只需删除这个对printf() 的不必要调用,它就会按预期工作。

    【讨论】:

      【解决方案3】:

      fgets() 从文件中逐行读取。来自fgets()的手册页

      如果读取了换行符,则将其存储到缓冲区中。

      fgets(buff_src, sizeof(buff_src), src) /* read upto New line or EOF from src and store into buff_src */
      

      当循环失败时,无论buff_src 包含使用最后一个printf 语句打印的内容。

      【讨论】:

        猜你喜欢
        • 2015-01-24
        • 2015-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多