fstream::close() doesn't close file

Ophir Yoktan Source

I have a program that reads a set of files, closes them, and then attempt to delete them.

Sometimes (not always, but pretty often) the delete fails with 'sharing violation' error.

Using sysinternals process monitor I saw that in these cases the close operation wasn't reflected in the process monitor.

It appears that sometimes the close system call is skipped for no apparent reason, and without any exception.

This is happening on a windows 7 64bit machine using visual studio 2010.

Code sample;

void readFile(string file)
  ifstream stream(file);
  string line;
  while(getline(stream, line))
    cout << line << endl:
  stream.close(); // this is redundant

// calling code:

if(remove(file.c_str()) != 0)
  cout << "file deletion failed" << endl;


answered 6 years ago Software_Designer #1

Firsty your code is lacking a ;. Change this cout << line << endl: to this cout << line << endl;

Here's a similar problem : Any reason why an std::ofstream object won't close properly?

answered 6 days ago trigg #2

This could happen if you are creating processes in-between using CreateProcess with bInheritHandles=true. The new process will inherit the file handle and the file won't be closed by your main process as there is still an outstanding handle. This may explain why you can't see the close operation in Process Monitor, the OS will close the file once all handles have been released.

comments powered by Disqus