c++ - fstream::close() 不关闭文件

标签 c++ visual-studio-2010 iostream

我有一个程序可以读取一组文件,关闭它们,然后尝试删除它们。

有时(不总是,但经常)删除失败并出现“共享违规”错误。

使用 sysinternals 进程监视器,我发现在这些情况下,关闭操作未反射(reflect)在进程监视器中。

似乎有时会无缘无故地跳过 close 系统调用,而且无一异常(exception)。

这是在使用 visual studio 2010 的 Windows 7 64 位机器上发生的。

代码示例;

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

//调用代码:

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

最佳答案

首先,您的代码缺少 ; .更改此 cout << line << endl:对此 cout << line << endl;

这里有一个类似的问题:Any reason why an std::ofstream object won't close properly?

关于c++ - fstream::close() 不关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8652793/

相关文章:

c++ - 模块化和灵活的编程

c++ - 使用 libusb 头文件

c# - streamWriter 重写文件或附加到文件

visual-studio-2010 - Visual Studio 2010 WebDev WebServer (Cassini) 64 位兼容吗?

c++ - std::iostream 如何缓冲?

C++ DirectX 绘制一个 .PNG Sprite 作为窗口背景

c++ - 为什么 cout << *s << endl 会产生段错误?

c++ - 是否有编译器警告是 Visual Studio 2013 检测复制的引用而不是通过引用分配的引用

c++ - std::setw() 和 ostream::width() 之间的类型不一致

c++ - 为什么 setw 和宽度不适用于 ostringstream?