我在 Unix 上编码。 我有一个文本文件作为输出。 如何在每次调用函数时覆盖内容?
例子:
functionA(){
fp = fopen("text.txt",someflag);
...
...blabla
....
fprintf(fp,"some new text");
}
因此,通过调用 functionA
,我应该得到包含新内容的 text.txt。
对于 someflag
,我已经尝试过 a
、ab
和 w+
,但都没有我想要的结果。 (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.
关于c - 如何覆盖文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029301/