简体   繁体   English

fstream :: close()不关闭文件

[英]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 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. 使用sysinternals进程监视器,我看到在这些情况下,关闭操作没有反映在进程监视器中。

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. 这是在使用Visual Studio 2010的Windows 7 64位计算机上发生的。

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;
}

This could happen if you are creating processes in-between using CreateProcess with bInheritHandles=true. 如果您正在使用带有bInheritHandles = true的CreateProcess在两者之间创建进程,则可能会发生这种情况。 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. 这可能可以解释为什么您无法在Process Monitor中看到关闭操作,一旦释放了所有句柄,操作系统就会关闭文件。

Firsty your code is lacking a ; 首先,您的代码缺少; . Change this cout << line << endl: to this cout << line << endl; 将此cout << line << endl:更改为此cout << line << endl;

Here's a similar problem : Any reason why an std::ofstream object won't close properly? 这是一个类似的问题: std :: ofstream对象无法正常关闭的任何原因?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM