0

I would like to know how the contents of a file can be cleared in *nix if it is open to write. (It may be a log file for example.)

braX
  • 11,506
  • 5
  • 20
  • 33
Mikhail
  • 7
  • 1
  • 4

1 Answers1

1

Take a look at fopen's manpage:

w

Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

so if you use

fp=fopen("file.txt", "w");

the contents of file.txt will be erased.

Update:

To delete a file's contents from command line use

printf "\0" > file.txt
rath
  • 3,655
  • 1
  • 40
  • 53
  • 2
    Note that what happens next depends on the flags that the program which has the file open for writing used in the call to `open()`. If the flags included `O_APPEND`, all is hunkydory. If they did not, the process will continue to write at the same position in the file that it was writing previously. The missing data between the start of the file and the write position will be treated as null bytes. When the process next writes to it, the file will grow back to larger than its previous size. It won't use all the disk space, but the file will still be larger than it was before it was truncated. – Jonathan Leffler Jan 19 '14 at 20:35