# C++ Remove - deleting a file

This topic is 2539 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Im trying to delete a file but its not really working.
I check if a file exists first, then if it does it should be deleted.

 FILE *pfile; pfile = fopen(fileName.c_str(), "w"); if(pfile != NULL) { if(remove(fileName.c_str()) != 0) ("Deletion Successful\n") else ("Deletion Unsuccessful\n") } fclose(pfile); 

The problem is that the remove function only seems to be removing the contents of the file and not deleteing it. From the name of the function that might sound reasonable i guess, but according to http://www.cplusplus.../cstdio/remove/ it deletes the file not just removes the contents. So after i call this the file still exists in the same directory it is just empty

##### Share on other sites
Streams usually operate with buffers. When you are writing to the file you are actually storing the data in a buffer, when it fills up or a certain amount of time has elapsed the buffer is "flushed" - actually written out to the disk. (As a side note this is why when you use streams for logging and such, in a program crash all of the data in the buffer might not get written out, and so your file ends before the program actually terminated).

In effect, what you are doing is:

creating an empty file, overwriting existing file (creates a stream)
deleting that file
closing the empty file (which flushes and closes the stream, writing the file out again)

You can move the fclose() above the remove()

 FILE *pfile; pfile = fopen(fileName.c_str(), "w"); if(pfile != NULL) { fclose(pfile); if(remove(fileName.c_str()) != 0) ("Deletion Successful\n") else ("Deletion Unsuccessful\n") } // don't need to close file here because pfile is NULL // fclose()'ing here would actually be undefined behavior 

##### Share on other sites
When you open a file to write, it clears it. Then you try to delete it. According to the link you gave, remove() returns 0 on success. So your condition is wrong. Remove might not work because on some runtimes/operating systems, the file is "locked" while it is open.

Why even check if the file exists? Let the remove() function do that too!

 if(remove(fileName.c_str()) == 0) { output("Deletion successful\n"); } else { output("Deletion unsuccessful\n"); } 

##### Share on other sites
Sorry, if I'm mistaken, but shouldn't you close() the file handle before trying to delete the file? CMIIW

1. 1
2. 2
Rutin
19
3. 3
khawk
18
4. 4
A4L
14
5. 5

• 12
• 16
• 26
• 10
• 44
• ### Forum Statistics

• Total Topics
633767
• Total Posts
3013735
×