printf覆盖,strcat仅追加文件的第一行 [英] printf overwriting, strcat appends only first line of the file

查看:91
本文介绍了printf覆盖,strcat仅追加文件的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

read.txt文件:

short
this is Longer
+++++
sad

和输出:

sad++is Longer
sad++is LongerWWWWWWWWWWWWWWWWWWWTFshort

当我满怀期待的时候:

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.

推荐答案

文本文件可能起源于具有"\r\n"行尾的平台

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

一个简单的解决方案利用了"\r"出现的可能性,它压倒了行尾的一部分,很容易被折断. strcspn()

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

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

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

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

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.

这篇关于printf覆盖,strcat仅追加文件的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆