c - 如何打开覆盖现有内容的文件

标签 c linux

我尝试在 Linux 中打开这样的文件。如果退出,它将覆盖现有的。这就是我想要的。

fout = open(out_file_name, O_WRONLY | O_CREAT, 644);

但是,如果现有的是1024字节,当我以上述方式打开并写入800个新字节时。 我仍然看到之前内容末尾的 224 字节。

我怎样才能让它只有我写的800字节?

最佳答案

您想将 O_TRUNC 标志用于 open(),方法是将其与上面现有的标志进行 OR 运算:

int fout = open(out_file_name, O_WRONLY | O_CREAT | O_TRUNC, 644);

这将截断文件。以下是 open(2) 手册页中的信息。

   O_TRUNC
          If the file already exists and is a regular file  and  the  open
          mode  allows  writing  (i.e.,  is O_RDWR or O_WRONLY) it will be
          truncated to length 0.  If the file is a FIFO or terminal device
          file,  the  O_TRUNC  flag  is  ignored.  Otherwise the effect of
          O_TRUNC is unspecified.

关于c - 如何打开覆盖现有内容的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23092040/

相关文章:

c - 使用c库函数设置系统时间

c - C语言中如何向数组追加值

在 C 编译期间更改函数体

c - 我的平衡支架解决方案有什么问题?

php - 在 Linux 上使用 php 连接访问 97

linux - 在 shell 脚本中执行 cp -u 时遇到问题

c - 为什么 scanf 在扫描整数时需要 & 而在扫描字符串时不需要 & ?

c - 必须将 ELF 文件的哪一部分加载到内存中?

linux - 使用 diff 比较特定行 linux 之间的文本

java - SELinux、Fedora 和 Trusted Applet 崩溃了?