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

Ori*_*ber 1 c printf fopen file

我正在尝试编写一个程序,为现有的txt文件添加行号.

例如,如果文件当前是:

Hello
this is
an
exercise
Run Code Online (Sandbox Code Playgroud)

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

(1) Hello
(2) this is
(3) an
(4) exercise
Run Code Online (Sandbox Code Playgroud)

我写了这段代码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

输出很奇怪.

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

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

当我在fopen中使用"r +"时,整个数据被删除,我所能看到的只有(1)然后是乱码.

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

S.C*_*sen 5

AFAIK你基本上不能在文件中间"插入"字节.相反,您将覆盖文件中的字节.因此,当您使用相同的文件进行读写时,您将"干扰自己".我建议您为写入输出创建一个临时文件,或者只写入标准输出,允许您将输出传递到合适的位置.