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?
The open() method takes two parameters as an argument: the path of the file and the mode either it can be a read mode 'r' or a write mode 'w'. To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode.
Select the Components tab and right-click on the component name. Select Details; the Component Details dialog appears. Mark the checkbox option to "Never overwrite if keypath exists." In addition, make sure that the file is the keypath of the Component in the File Key Path field. Click OK.
Overwriting is the rewriting or replacing of files and other data in a computer system or database with new data. One common example of this is receiving an alert in Microsoft Word that a file with the same name already exists and being prompted to choose whether you want to restore the old file or save the new one.
file_put_contents does not overwrite the existing content for me, it just appends it to the end.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With