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

时间:2014-04-15 18:53:33

标签: c linux

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

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

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

如何让它只有我写的800字节?

1 个答案:

答案 0 :(得分:19)

您希望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.