printf overwriting, strcat appends only first line of the file

我怕爱的太早我们不能终老 提交于 2019-12-13 03:22:06

问题


I am after a simple task: reading one line at a time from a file, printing the line and appending all the content in a char array. It all started with a Segmentation fault (core dumped) from my project, I then kept on isolating my code until I reached this:

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

The read.txt file:

short
this is Longer
+++++
sad

And the Output:

sad++is Longer
sad++is LongerWWWWWWWWWWWWWWWWWWWTFshort

When I was confidently expecting:

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

I have been over multiple similar questions and most answers refer to carriage return but I still don't understand this behavior and what is the cause for it.


回答1:


The text file likely originated on a platform with "\r\n" line endings @M.M.

A simple solution takes advantage the should "\r" occur, it is overwhelming part of the line ending and can easily be lopped off. strcspn()

I now see @David C. Rankin suggested this.

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

Unfortunately when a text file line-endings employ "\r" only, fgets() (on a system expecting "\n") will not see any line ending. There a new approach is needed.




回答2:


As I am using Linux, the problem was with the input file. After running file read I got read: ASCII text, with CR line terminators and the CR LT were causing that stage overwriting behavior. Created a new input file newFile: ASCII text with the same text and the output was as expected.



来源:https://stackoverflow.com/questions/54084577/printf-overwriting-strcat-appends-only-first-line-of-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!