Search code examples
visual-c++file-iomemory-mapped-files

Memory Mapped File Code Not Working Correctly in C++


I am trying to read large files by mapping them to the memory for better efficiency. After opening the file, creating memory map object, and view, I am trying to access the values in the file by dereferencing the pointer to the memory, but I am not getting the actual values in the file.

For a small experiment, I am trying to read the values in the following file "test.txt" which includes 4 integers as 1 2 3 4

Here is my code.

HANDLE hCreateFile;
HANDLE hMapFile;
LPVOID lpMapAddress;
char tempFile[200];
strcpy(tempFile,"C:\\...\\test.txt");
hCreateFile = CreateFile(tempFile,GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);   //Opens the "tempFile" and returns an handle to the file

if(hCreateFile == INVALID_HANDLE_VALUE) {
    std::cout<<"Problem opening the file"<<std::endl;
}

hMapFile = CreateFileMapping(hCreateFile, NULL, PAGE_READONLY, 0, 0, 0);
if(hMapFile == 0)   {
    std::cout<<"Problem creating map file object"<<std::endl;
}

lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
if(lpMapAddress == 0){
    std::cout<<"Problem viewing the file"<<std::endl;
}

int* mp = (int*)lpMapAddress;
std::cout<<"The first dose value is "<<*mp<<" ";
std::cout<<"The second dose value is "<<*(mp+1)<<" ";
std::cout<<"The third dose value is "<<*(mp+2)<<" ";
std::cout<<"The fourth dose value is "<<*(mp+3)<<;

From this code, the output that I expect to get is 1 2 3 4

However, I am getting something like this 221388849 874525450 0 0

Could anybody help me with what I am doing wrong in the code above? Thank you.


Solution

  • It looks like you are reading ASCII data and expecting a magical conversion to integers.

    Think about what the text is:

    "1 2 3 4"

    Now your first value: 221388849

    The is 0x0D322031

    0x31 = "1" 0x20 = " " ox32 = "2"

    ... and so on.