Ophir Yoktan
Ophir Yoktan

Reputation: 8449

fstream::close() doesn't close file

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 deletion 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:

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

Upvotes: 2

Views: 4041

Answers (2)

trigg
trigg

Reputation: 56

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.

Upvotes: 0

Software_Designer
Software_Designer

Reputation: 8587

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?

Upvotes: 0

Related Questions