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

时间:2022-12-29 21:15:37

I try to open a file like this in linux. It will over-write an existing one if exits. That is what I want.

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

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

However, if the existing is 1024 bytes, when I open in above way and write 800 new bytes. I still see the 224 bytes at the end of previous content.

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

How can I make it just have the 800 bytes that I have been written?

我怎么能让它只有我写的800字节呢?

1 个解决方案

#1


11  

You want to use the O_TRUNC flag to open(), by OR-ing it with the existing flags you have above:

您希望使用O_TRUNC标志来打开(),方法是使用上面已有的标志对其进行OR-ing:

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

This will truncate the file. Below is the information in the man page for open(2).

这将截断文件。下面是打开(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.

#1


11  

You want to use the O_TRUNC flag to open(), by OR-ing it with the existing flags you have above:

您希望使用O_TRUNC标志来打开(),方法是使用上面已有的标志对其进行OR-ing:

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

This will truncate the file. Below is the information in the man page for open(2).

这将截断文件。下面是打开(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.