Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear the contents of a file

Tags:

c

unix

I would like to know how the contents of a file can be cleared in C. I know it can be done using truncate, but I can't find any source clearly describing how.

like image 390
mousey Avatar asked Nov 28 '22 11:11

mousey


1 Answers

The other answers explain how to use truncate correctly... but if you found yourself on a non-POSIX system that doesn't have unistd.h, then the easiest thing to do is just open the file for writing and immediately close it:

#include <stdio.h>

int main()
{
    FILE *file = fopen("asdf.txt", "w");
    if (!file)
    {
        perror("Could not open file");
    }

    fclose(file);
    return 0;
}

Opening a file with "w" (for write mode) "empties" the file so you can start overwriting it; immediately closing it then results in a 0-length file.

like image 186
Mark Rushakoff Avatar answered Dec 06 '22 10:12

Mark Rushakoff