【发布时间】:2014-10-08 08:56:51
【问题描述】:
我正在使用 VS2010 用 C++ 编写一个程序来读取文本文件并从中提取某些信息。我使用文件流完成了代码,它运行良好。但是现在我被要求将文件映射到内存并使用它而不是文件操作。
在内存映射的情况下,我绝对是新手。我写的部分代码如下。
boost::iostreams::mapped_file_source apifile;
apifile.open(LogFileName,LogFileSize);
if(!apifile.is_open())
return FILE_OPEN_ERROR;
// Get pointer to the data.
PBYTE Buffer = (PBYTE)apifile.data();
while(//read till end of the file)
{
// read a line and check if it contains a specific word
}
在使用文件流时,我会使用 eof 和 getline 和 string::find 来执行操作。但我不知道如何使用内存映射文件来做到这一点。
编辑 1:
int ProcessLogFile(string file_name)
{
LogFileName = file_name;
apifile.open(LogFileName);//boost::iostreams::mapped_file_source apifile(declared globally)
streamReader.open(apifile, std::ios::binary);//boost::iostreams::stream <boost::iostreams::mapped_file_source> streamReader(declared globally)
streamoff Curr_Offset = 0;
string read_line;
int session_id = 0;
int device_id = 0;
while(!streamReader.eof())
{
\\COLLECT OFFSETS OF DIFFERENT SESSIONS
}
streamReader.close();
}
这个函数有效,我得到了所需结构的偏移量。
现在调用这个函数后,我又调用了另一个函数,如下:
int GetSystemDetails()
{
streamReader.open(apifile, std::ios::binary);
string read_line;
getline(streamReader,read_line);
cout << "LINE : " << read_line;
streamReader.close();
}
我在 read_line 中没有得到任何数据。该内存映射仅适用于单个功能吗?如何在不同的函数中使用相同的内存映射文件?
【问题讨论】:
-
文件很大吗?您需要文件映射吗?
-
@MarcoA。 : 是的,我需要文件映射。该文件具有动态性质,大小主要为 MB。
-
mapped_file_source有data()和size()方法,你当然可以将data()返回的指针增加到size()倍? -
@sjdowling:你介意举个小例子吗?
标签: c++ visual-studio-2010 memory boost