我正在尝试编写一个程序,为现有的txt文件添加行号.
例如,如果文件当前是:
Hello this is an exercise
然后运行代码后,它将是:
(1) Hello (2) this is (3) an (4) exercise
我写了这段代码:
#include#include 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)和乱码.