How to open a file which overwrite existing content
c, linux
Solution
You want to use the `O_TRUNC` flag to `open()`, by OR-ing it with the existing flags you have above:
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).
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.
Problem
I try to open a file like this in linux. It will over-write an existing one if exits. That is what I want. ``` 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. How can I make it just have the 800 bytes that I have been written?