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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With