Reputation: 1
fopen example
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
FILE * pFile;
for(int i=0; i < 1000000; i++)
{
bool ret = remove("C:\\abc.txt");
pFile = fopen ("C:\\abc.txt","w");
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
fclose (pFile);
}
else
{
printf("%d fopen() fails \n", count);
}
}
return 0;
}
Here, after remove is called, pFile = fopen ("C:\abc.txt","w");is called,
Sometimes even in C:\ the abc.txt file is not present after remove called, but the fopen pFile pointer is null.
This is reproduced some times not always. In this example this issue is reproduced 50/60 times.
Please suggest some solution.
Upvotes: 0
Views: 267
Reputation: 1980
If you need to create a file surely after the file was removed, you can delay the fopen until you confirm that the old "abc.txt" file removed.
For that you need to introduce some loop to confirm it like below,
bool ret = remove("C:\\abc.txt");
FILE * rFile;
while(true)
{
rFile = fopen ("C:\\abc.txt","r");
if(rfile == null)
break; //File Removed confirmed!!
else
sleep(100); //Loop around again...
}
pFile = fopen ("C:\\abc.txt","w");
if (pFile!=NULL)
Upvotes: 0
Reputation: 148910
If you have already established that is is a problem of race condition in the underlying file system, the correct way to fix it is (as suggested by BLUEPIXY) to simply remove the remove
call :
pFile = fopen ("C:\\abc.txt","w");
will create the file if it does not exist and truncate it to 0 size if it exists, what is exactly what you need.
Upvotes: 1