使用std::ifstream强制读取磁盘,而不是文件缓存
Force read on disk with std::ifstream instead of the file cache
我有一个程序,使用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()
正在做您想要的吗?
操作系统使用文件缓冲区来提高磁盘性能的事实通常在应用程序级别是不可见的。只要你在看同一个文件,操作系统就知道用户更新了文件,如果你重新打开它,你就会看到改变的数据。如果数据甚至从来没有机会被刷新到磁盘,这不会影响您的应用程序。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在文件系统之上添加层?就像OneDrive或Google云端硬盘中的缓存一样
- 如何指定创建文件函数获取未缓存的结果?
- 为什么此CMAKE初始缓存文件会导致如此奇怪的错误
- Make/g 的缓存标头文件
- C++实现文件缓存(如 Web 浏览器)的库
- 哪个文件在Windows Embedded Compact 7.0上配置缓存
- 如何找到IE浏览器缓存文件的完整路径?
- 删除IE中"缓存清除"上的文件
- 正在禁用c++代码的文件缓存
- 如何写入文件,然后将其读回以验证其内容,确保您获得的是磁盘上的内容而不是缓存
- 使用std::ifstream强制读取磁盘,而不是文件缓存
- 使用FILE_FLAG_RANDOM_ACCESS访问文件,并限制缓存大小
- 缓存对象应该直接从文件系统中读取吗?
- 如何在c++中创建临时文件来帮助缓存大数据
- 为什么写入文件会增加缓存未命中和分支未命中这么多
- c++视口缓存目录中的文件