c - 如何覆盖文本文件?

标签 c unix printf fopen

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

例子:

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

因此,通过调用 functionA,我应该得到包含新内容的 text.txt。

对于 someflag,我已经尝试过 aabw+,但都没有我想要的结果。 (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/

相关文章:

java - 为什么 user.dir 可以设置为 "."?

c - 在 C 中的 bmp 图像之间导航/滚动

c - 使用字符串表 "decoder ring"的 printf() 调试库

c - 我应该更改什么以便我的 arctan(x) 近似可以正确显示 x=1 和 x=-1?

mysql - C程序中的"unable to include mysql.h"

cocoa - 将 Unix 实用程序打包为 Cocoa 应用程序的一部分

Bash ls 和命令管道

c - fprintf 没有打印到文件

c++ - 重叠缓冲区的 memcpy

c - 我在接受技术面试时被要求制作这样的结构..