printf 覆盖,strcat 仅附加文件的第一行
printf overwriting, strcat appends only first line of the file
我正在执行一项简单的任务:一次从 文件 中读取一行,打印该行并将所有内容附加到一个字符数组中。这一切都从我的项目中的 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,但我仍然不明白这种行为及其原因。
因为我正在使用 Linux,问题出在输入文件上。在 运行 file read
之后,我得到了 read: ASCII text, with CR line terminators
并且 CR LT 导致了该阶段的覆盖行为。使用相同的文本创建了一个新的输入文件 newFile: ASCII text
,输出符合预期。
文本文件可能源自具有 "\r\n"
行结尾 的平台。
一个简单的解决方案利用了应该 "\r"
发生的优势,它是行尾的压倒性部分,很容易被删除。 strcspn()
我现在看到 建议了这个。
while(fgets(buffer, sizeof buffer, fp)) {
// Find length of string not made up of '\n', '\r', '[=10=]'
// This nicely lops off the line ending, be it "\n", "\r\n" or missing.
buffer[strcspn(buffer, "\n\r")] = '[=10=]';
printf("<%s>\n",buffer);
}
不幸的是,当文本文件行尾仅使用 "\r"
时,fgets()
(在需要 "\n"
的系统上)将看不到任何行尾。需要一种新方法。
我正在执行一项简单的任务:一次从 文件 中读取一行,打印该行并将所有内容附加到一个字符数组中。这一切都从我的项目中的 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,但我仍然不明白这种行为及其原因。
因为我正在使用 Linux,问题出在输入文件上。在 运行 file read
之后,我得到了 read: ASCII text, with CR line terminators
并且 CR LT 导致了该阶段的覆盖行为。使用相同的文本创建了一个新的输入文件 newFile: ASCII text
,输出符合预期。
文本文件可能源自具有 "\r\n"
行结尾
一个简单的解决方案利用了应该 "\r"
发生的优势,它是行尾的压倒性部分,很容易被删除。 strcspn()
我现在看到
while(fgets(buffer, sizeof buffer, fp)) {
// Find length of string not made up of '\n', '\r', '[=10=]'
// This nicely lops off the line ending, be it "\n", "\r\n" or missing.
buffer[strcspn(buffer, "\n\r")] = '[=10=]';
printf("<%s>\n",buffer);
}
不幸的是,当文本文件行尾仅使用 "\r"
时,fgets()
(在需要 "\n"
的系统上)将看不到任何行尾。需要一种新方法。