使用std::ifstream强制读取磁盘,而不是文件缓存

Force read on disk with std::ifstream instead of the file cache

本文关键字:文件 缓存 读取 ifstream std 使用 磁盘      更新时间:2023-10-16

我有一个程序,使用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();
}

谢谢。

编辑:当然,这是一个错误,因为我有两次相同的文件在两个非常相似的路径。查看进程资源管理器打开的文件句柄(而不是相对文件路径使我找到它)。

与其认为这是由于某种"缓冲",不如先寻找明显的东西。

  • 您确定用户正在更改您正在读取的同一个文件吗?
  • 你确定重新加载数据是正确更新内存中的数据结构吗?
  • 您确信DataValid()正在做您想要的吗?

操作系统使用文件缓冲区来提高磁盘性能的事实通常在应用程序级别是不可见的。只要你在看同一个文件,操作系统就知道用户更新了文件,如果你重新打开它,你就会看到改变的数据。如果数据甚至从来没有机会被刷新到磁盘,这不会影响您的应用程序。