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.)
Asked
Active
Viewed 135 times
0
-
What language are you using btw? – rath May 23 '13 at 15:12
-
Can I do it just in a command line without any language using? – Mikhail May 23 '13 at 15:15
-
`> file` can make it - it truncates the file. – fedorqui May 23 '13 at 15:20
-
Even if it open by another program? – Mikhail May 23 '13 at 15:27
-
possible duplicate of [How to truncate a file in C?](http://stackoverflow.com/questions/873454/how-to-truncate-a-file-in-c) – Jonathan Leffler Jan 19 '14 at 20:36
1 Answers
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
-
2Note 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