gpt4 book ai didi

c - C 中的 fopen 和 fprintf 没有按预期工作?

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:20 28 4
gpt4 key购买 nike

我正在尝试编写一个程序,将行号添加到一个已经存在的 txt 文件中。

例如,如果文件当前是:

Hello
this is
an
exercise

然后运行代码后,它将是:

(1) Hello
(2) this is
(3) an
(4) exercise

我写了这段代码:

#include<stdio.h>
#include<conio.h>
FILE *fp;
void main()
{
int counter=1;
char newline;
fp=fopen("G:\\name.txt","r+");
if(fp==NULL)
printf("Failed to open file!");
fprintf(fp,"(%d)",counter);
newline=fgetc(fp);
while(newline!=EOF)
{
if(newline=='\n')
{
counter++;
fprintf(fp,"(%d)",counter);
}
newline=fgetc(fp);
}
printf("All done!");
getch();
fclose(fp);
}

而且输出很奇怪。

首先,它不会在文件开头打印。由于某种原因,它从文件末尾开始。发生的另一件奇怪的事情是只有第一次打印成功。

while 循环中的那些是乱码(看起来像小点,根本不像数字)

当我在 fopen 中使用“r+”时,整个数据都被删除,我只能看到 (1),然后是乱码。

如果我在 fopen 中使用“a+”,它会从文件末尾开始,然后写入 (1) 和乱码。

最佳答案

据我所知,您基本上不能在文件中间“插入”字节。相反,您将覆盖文件中的字节。因此,当您使用同一个文件进行读写时,您将“干扰自己”。我建议您为写入的输出创建一个临时文件,或者只写入标准输出,这样您就可以将输出通过管道传输到合适的位置。

关于c - C 中的 fopen 和 fprintf 没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24604279/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com