如何用C覆盖文件?

czc*_*ong 7 c file-io

我试图用C覆盖FILE的内容.目前我有:

FILE* file  = fopen("filename.txt",  "r+");
fprintf(file, "%d", 1); // regardless of what's in the file, i want to clear it and put 1 in there
...
// legacy code somewhere else in the code base. can't change.
rewind(file);
fprintf(file, "%d", 2);
fflush(file);
Run Code Online (Sandbox Code Playgroud)

但是,这将无法正常工作.结果将是:

1,21

每个后续编号将写入1的开头.例如:

1,21,31,41,......

我想知道是否有办法总是覆盖文件中的内容,以便生成以下内容:

1,2,3,4 ......

任何援助将不胜感激.

谢谢.

编辑:

我已将代码更改为:

FILE* file  = fopen("filename.txt",  "w+");
Run Code Online (Sandbox Code Playgroud)

问题仍然存在.

Bo *_*son 15

你决定在fopen.只需使用"w""w+"代替"r+".