【发布时间】:2011-11-01 00:43:55
【问题描述】:
我有一个程序,它使用 std::ifstream 从文件加载数据并将数据存储在一个结构中。之后,我验证我想要的数据是否在文件中。如果不是,我要求用户修改文件并按一个键。然后我重新加载文件。问题是即使用户修改了文件,我总是在文件中得到相同的数据,因为文件似乎在应用程序中缓存。我已经看到在 win32 API 中,可以使用标志 FILE_FLAG_NO_BUFFERING 来避免在读取文件时使用缓冲副本,但我想将该功能与 std::ifstream 一起使用。有没有办法将通过 win32 api 创建的句柄与 ifstream 一起使用,或者直接在 std::ifstream 中强制它?
这是一个“简化”的代码示例:
SomeStructure s = LoadData(fileName);
while(!DataValid(s))
s = LoadData(fileName);
SomeStructure LoadData(const std::string& fileName)
{
std::ifstream fileStream;
while(!OpenFileRead(fileName, fileStream))
{
std::cout<<"File not found, please update it";
fileStream.close();
//Wait for use input
std::string dummy;
std::getline(std::cin, dummy);
}
//... Read file, fill structure, and return
std::string line;
while(std::getline(fileStream, line) && line!="")
{
//At this point, I can see that line is wrong
StringArray namedatearray=Utils::String::Split(line, "|");
assert(namedatearray.size()==2);
//Add data to my structure ( a map)
}
fileStream.close();
//return structure
}
bool OpenFileRead(const std::string& name, std::fstream& file)
{
file.open(name.c_str(), std::ios::in);
return !file.fail();
}
谢谢。
编辑:当然,这是一个错误,因为我在两个非常相似的路径中有两次相同的文件。查看使用进程资源管理器打开的文件的句柄(而不是相对文件路径让我找到它)。
【问题讨论】:
-
无缓冲 IO 在这里没有任何意义。你要么有错误的写入代码或有错误的读取代码。
-
如果问题出在应用程序中的缓存,正如您所声称的,那么无缓冲 I/O 对您没有帮助,因为无缓冲 I/O 意味着 内核中没有缓冲。它与应用程序的缓存数据无关。而且您不太可能让
ifstream使用无缓冲句柄,因为when you create an object with constraints, you have to make sure everybody who uses the object understands those constraints。 -
你是如何修改文件的?我们认为“修改”文件的许多事情实际上根本不修改文件,而是用修改后的新文件替换文件。
-
对于编写代码,修改是用普通的旧记事本完成的(并在之后立即保存)。至于读取的部分,我已经在代码中添加了。
标签: c++ windows caching std ifstream