I wrote a program, in which my code is checking the word entered by user and the word in a file. If the words are not same, the file is deleted.
i closed the file using fclose(fp), (where fp is file pointer)
and to delete the file i used system("del filename.txt").
But, i get a messsage saying that the file is in use by another process.
My question is HOW?? When I closed the file then how it can be in use of some other process??
Need assistance on this ... thanks!!

5 Years
Discussion Span
Last Post by Vish0203

My question is HOW?? When I closed the file then how it can be in use of some other process??

My gut reaction is to say that this is a timing issue, but it's possible that fclose() failed. First try testing the return value to see if there were any problems:

if (fclose(fp)) {
    perror("Failed to close the file");

If fclose() succeeds then to check if it's a timing issue, where the OS is still holding onto the handle because flush and close requests are queued and haven't completed, you can try sleeping for a bit to give the OS time to catch up:

#include <stdbool.h>
#include <windows.h>



bool removed = false;

/* Try a few times with a pause inbetween */
for (int i = 0; i < 3; ++i) {
    if (remove("filename.txt") == 0) {
        removed = true;


if (!removed) {
    fputs("File was not deleted\n", stderr);

You may need to play with the pause amounts and number of attempts, but the above has worked well for me in catching any timing issues. 200ms is actually quite huge, and often far less than that works just fine.


Didn't work for me!! :(
it always displays stderr part. tried pausing the process for 1000 and 2000 too.. same thing happens... shall I post the actual code?


Please do, if it's not excessively long.

I solved the problem, by closing the file way before getting to this part of code.. it works fine now... But, I don't know why the Sleep() is not making any difference!! :/

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.