printf覆盖,strcat仅附加文件的第一行

时间:2019-01-08 02:44:09

标签: c file printf stdout

我的任务很简单:一次从文件中读取一行,打印该行并将所有内容附加到char数组中。一切都从我的项目中的Segmentation fault (core dumped)开始,然后我继续隔离我的代码,直到达到目标为止:

#include <stdio.h>
#include <string.h>
int main(void)
{
    FILE *fp;
    fp = fopen("read.txt","r");
    char buffer[255];
    char longBuff[1024] = "";
    while(fgets(buffer, 255, fp)) {
        printf("%s\n",buffer);
        strcat(longBuff, buffer);
    }
    fclose(fp);
    printf("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTF%s\n", longBuff);
}

read.txt文件:

short
this is Longer
+++++
sad

和输出:

sad++is Longer
sad++is LongerWWWWWWWWWWWWWWWWWWWTFshort

当我满怀期待的时候:

short
this is Longer
+++++
sad
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWTFshortthis is Longer+++++sad

我遇到过多个类似的问题,大多数答案都指向carriage return,但我仍然不了解这种行为及其原因。

2 个答案:

答案 0 :(得分:2)

该文本文件可能起源于以"\r\n"行结尾为@M.M的平台。

一个简单的解决方案利用了"\r"出现时的优势,它压倒了行尾的一部分,可以很容易地断开。 strcspn()

我现在看到@David C. Rankin提出了这个建议。

while(fgets(buffer, sizeof buffer, fp)) {
  // Find length of string not made up of '\n', '\r', '\0'
  // This nicely lops off the line ending, be it "\n", "\r\n" or missing.
  buffer[strcspn(buffer, "\n\r")] = '\0';
  printf("<%s>\n",buffer);
}

不幸的是,当文本文件的行尾仅使用"\r"时,fgets()(在期望"\n"的系统上)将看不到任何行尾。需要一种新方法。

答案 1 :(得分:0)

当我使用Linux时,问题出在输入文件上。运行file read之后,我得到了read: ASCII text, with CR line terminators,CR LT导致了该阶段的覆盖行为。用相同的文本创建了一个新的输入文件newFile: ASCII text,并且输出符合预期。