如何覆盖文本文件?

How to overwrite a text file?

我在 Unix 上编码。 我有一个文本文件作为输出。 每次调用函数时如何覆盖内容?

示例:

functionA(){
    fp = fopen("text.txt",someflag);
    ...
    ...blabla
    ....
    fprintf(fp,"some new text");
}

所以通过调用 functionA,我应该 text.txt 有新内容。

对于someflag,我已经尝试了aabw+,但是none得到了我想要的结果。 (ab 追加新文本,w+ 打开文件,但 fprintf 不起作用)。 我在 unix 上使用 C。

标记 "w" 应该覆盖现有文件。

详情见this documentation,具体为:

The mode argument points to a string. If the string is one of the following, the file shall be opened in the indicated mode. Otherwise, the behavior is undefined.

  • r or rb: Open file for reading.
  • w or wb: Truncate to zero length or create file for writing.
  • a or ab: Append; open or create file for writing at end-of-file.
  • r+ or rb+ or r+b: Open file for update (reading and writing).
  • w+ or wb+ or w+b: Truncate to zero length or create file for update.
  • a+ or ab+ or a+b: Append; open or create file for update, writing at end-of-file.