Search code examples
fileunixtruncate

How to clear the contents of an open file in *nix


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.)


Solution

  • 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