Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file which overwrite existing content

Tags:

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?

like image 259
n179911 Avatar asked Apr 15 '14 18:04

n179911


People also ask

How do I open an overwritten file?

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.

How do I stop a file from overwriting?

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.

What does overwrite existing files mean?

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.

Does file put contents Overwrite?

file_put_contents does not overwrite the existing content for me, it just appends it to the end.


1 Answers

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. 
like image 64
Dan Fego Avatar answered Sep 21 '22 14:09

Dan Fego