Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
fopen example */
C++
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
  FILE * pFile;
  for(int i=0; i &lt; 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.

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 26-Oct-14 23:44pm
v2
Comments
Jochen Arndt 27-Oct-14 5:53am    
It may be a file system caching issue. You may print out the content of the global errno variable to know which kind of error occured (include errno.h).
Fredrik Bornander 27-Oct-14 5:53am    
Is it the remove call that fails? Have you tried checking the ret variable for false?

The functions you use give no reason to expect an issue, so I can't say what causes this. (although Jochens suggestion - a caching issue - seems plausible)

However, there is no need to call remove at all if you open the file for writing anyway: if the file already exists, it will be emptied and treated as new. See http://www.cplusplus.com/reference/cstdio/fopen/[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900