Search code examples
cfile

Remove contents of file with fopen("file_name.dat","w")


Is it safe and acceptable to opening a file and immediately close it to simply remove its contents.

FILE *fp = fopen("file_name.dat","w");
fclose(fp);

I try it and works fine for me. what is recommended method? Please explain other way(s) of doing it. Not duplicate of truncate file I want to know is this way to remove a file true because I guess it and not read it in any books


Solution

  • There are multiple ways you can achieve it. It all depends on your use case. Few of them are as follows:

    1. As you have suggested but with few checks
    FILE *fp = fopen("file_name.dat","w"); /*fopen("file_name.dat","wb");*/
    if(fp)
    {
        fclose(fp);
    }
    
    

    It is better to check for the fopen return.

    1. You can remove the file altogether and open the file again. https://www.tutorialspoint.com/c_standard_library/c_function_remove.htm