我有一个程序可以读取一组文件,关闭它们,然后尝试删除它们。
有时(不总是,但经常)删除失败并出现“共享违规”错误。
使用 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/