Windows create file in memory

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Отображением файла в память мы с вами пользовались в заметках об OpenGL, посвященных работе с моделями и текстурами, но не рассматривали подробно, как именно это работает. И хотя я почти уверен, что многие читатели этого блога уже знакомы с отображением файлов в память, я все же посчитал необходимом написать соответствующие заметки для тех читателей, кому данный механизм не знаком. Сегодня мы рассмотрим, как все это работает под Windows.

Заведем такую структуру, хранящую хэндл файла, хэндл отображения, размер файла, а также указатель на участок памяти с отображением:

#include <windows.h>

struct FileMapping {
  HANDLE hFile;
  HANDLE hMapping;
  size_t fsize;
  unsigned char* dataPtr;
};

Рассмотрим чтение из файла с использованием отображения.

Открываем файл:

HANDLE hFile = CreateFile(fname, GENERIC_READ, 0, nullptr,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL, nullptr);
if(hFile == INVALID_HANDLE_VALUE) {
  std::cerr << «fileMappingCreate — CreateFile failed, fname = «
            << fname << std::endl;
  return nullptr;
}

С процедурой CreateFile мы уже знакомы по заметке Учимся работать с файлами через Windows API, поэтому двигаемся дальше.

Получаем размер файла:

DWORD dwFileSize = GetFileSize(hFile, nullptr);
if(dwFileSize == INVALID_FILE_SIZE) {
  std::cerr << «fileMappingCreate — GetFileSize failed, fname = «
            << fname << std::endl;
  CloseHandle(hFile);
  return nullptr;
}

Вторым аргументом процедура GetFileSize получает указатель на DWORD для записи старшей части размера файла. Передав в качестве этого аргумента nullptr, мы ограничили размер файла, который может вернутся. Если размер файла будет 4 Гб или больше, процедура вернет ошибку.

Создаем отображение:

HANDLE hMapping = CreateFileMapping(hFile, nullptr, PAGE_READONLY,
                                    0, 0, nullptr);
if(hMapping == nullptr) {
  std::cerr << «fileMappingCreate — CreateFileMapping failed, fname = «
            << fname << std::endl;
  CloseHandle(hFile);
  return nullptr;
}

Заметьте, что hMapping проверяется на равенство nullptr. Это не баг — согласно MSDN, в случае ошибки CreateFileMapping действительно возвращает пустой указатель, а не INVALID_HANDLE_VALUE, как можно было бы ожидать. Такая неконсистентность, к сожалению, встречается время от времени в WinAPI. Мы уже встречались с этой проблемой, изучая работу с реестром.

Наконец, получаем указатель на участок памяти с отображением, используя процедуру MapViewOfFile:

unsigned char* dataPtr = (unsigned char*)MapViewOfFile(hMapping,
                                                       FILE_MAP_READ,
                                                       0,
                                                       0,
                                                       dwFileSize);
if(dataPtr == nullptr) {
  std::cerr << «fileMappingCreate — MapViewOfFile failed, fname = «
            << fname << std::endl;
  CloseHandle(hMapping);
  CloseHandle(hFile);
  return nullptr;
}

Затем заполняем структуру FileMapping и возвращаем указатель на нее в качестве результата:

FileMapping* mapping = (FileMapping*)malloc(sizeof(FileMapping));
if(mapping == nullptr) {
  std::cerr << «fileMappingCreate — malloc failed, fname = «
            << fname << std::endl;
  UnmapViewOfFile(dataPtr);
  CloseHandle(hMapping);
  CloseHandle(hFile);
  return nullptr;
}

mapping>hFile = hFile;
mapping>hMapping = hMapping;
mapping>dataPtr = dataPtr;
mapping>fsize = (size_t)dwFileSize;

return mapping;

Теперь читая mapping->fsize байт памяти по адресу mapping->dataPtr можно получить содержимое файла.

Когда отображение становится ненужным, не забываем его закрыть:

UnmapViewOfFile(mapping>dataPtr);
CloseHandle(mapping>hMapping);
CloseHandle(mapping>hFile);
free(mapping);

Как видите, все предельно просто. Исходники к этой заметке вы найдете здесь.

В качестве домашнего задания можете попробовать модифицировать код так, чтобы через отображение файл можно было не только читать, но и писать в него.

Задание со звездочкой для желающих — ответьте на следующий вопрос. Можно ли, работая с отображением файла в память, менять его размер, например, делать append или обрезать файл посередине, и если можно, то как? Если честно, я сам так с лету не готов ответить на этот вопрос, потому что такой задачи передо мной не вставало. Так что, с нетерпением жду ваших вариантов ответа в комментариях!

Дополнение: Пример отображения файла в память под Linux и MacOS

Метки: C/C++, WinAPI.

  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Create and Save file in Memory

  1. Nov 2nd, 2006, 11:02 AM


    #1

    Create and Save file in Memory

    Dear How can I create file that is stored in only in memory not in the physical drive.SO that I can avoid the user editing it?

    Thanks in advance


  2. Nov 2nd, 2006, 11:03 AM


    #2

    Re: Create and Save file in Memory

    I asked a similar question once, for pretty much the same reason…security. It was highly difficult back then so don’t expect it to be at all easy now :-)

    Well, everyone else has been doing it :-)
    Loading a file into memory QUICKLY — Using SendKeys — HyperLabel — A highly customisable label replacement — Using resource files/DLLs with VB — Adding GZip to your projects
    Expect more to come in future
    If I have helped you, RATE ME! :-)

    I love helping noobs with their VB problems (probably because, as an amateur programmer, I am only slightly better at VB than them :-)) but if you SERIOUSLY want to get help for free from a community such as VBForums, you have to first have a grounding (basic knowledge) in VB6, otherwise you’re way too much work to help…You’ve got to give a little if you want to get help from us, in other words!

    And we DON’T do your homework. If your tutor doesn’t teach you enough to help you make the project without his or her help, FIND A BETTER TUTOR or try reading books on programming! We are happy to help with minor things regarding the project, but you have to understand the rest of it if you want our help to be useful.


  3. Nov 2nd, 2006, 11:04 AM


    #3

    Re: Create and Save file in Memory

    I think that’s what ROM is for (Read-Only Memory) and i think you can’t edit it.


  4. Nov 2nd, 2006, 11:06 AM


    #4

    Re: Create and Save file in Memory

    Dear Gavio,
    Is it posible or not.The file types i want to create are Text,Word,XML and Html


  5. Nov 2nd, 2006, 11:11 AM


    #5

    Re: Create and Save file in Memory

    ROM, as its name suggests, is READ ONLY memory and is in no way usable for storing data…the closest you can get is EEPROMs like the BIOS (EEPROM, also known as EPROM, means electrically erasable programmable read-only memory) which *is* rewritable like that…flash memory is similar but I don’t know how similar it is though :-)

    Writing a program to memory is doable…however, executing it from directly in memory is a lot harder because of antivirus security (that’s exactly how viruses used to propagate :-))

    Edit: However, if you’re creating text files they won’t be executed…so that should be doable :-)

    Well, everyone else has been doing it :-)
    Loading a file into memory QUICKLY — Using SendKeys — HyperLabel — A highly customisable label replacement — Using resource files/DLLs with VB — Adding GZip to your projects
    Expect more to come in future
    If I have helped you, RATE ME! :-)

    I love helping noobs with their VB problems (probably because, as an amateur programmer, I am only slightly better at VB than them :-)) but if you SERIOUSLY want to get help for free from a community such as VBForums, you have to first have a grounding (basic knowledge) in VB6, otherwise you’re way too much work to help…You’ve got to give a little if you want to get help from us, in other words!

    And we DON’T do your homework. If your tutor doesn’t teach you enough to help you make the project without his or her help, FIND A BETTER TUTOR or try reading books on programming! We are happy to help with minor things regarding the project, but you have to understand the rest of it if you want our help to be useful.


  6. Nov 2nd, 2006, 11:13 AM


    #6

    Re: Create and Save file in Memory

    Originally Posted by danasegarane

    The file types i want to create are Text,Word,XML and Html

    Why not just put them into a string? Surely that’s «saving to memory»!

    What you need to do is give us more information about what you plan to do with it…if you want many programs to have access, for instance, whether it needs to remain there after the program closes, etc.

    Well, everyone else has been doing it :-)
    Loading a file into memory QUICKLY — Using SendKeys — HyperLabel — A highly customisable label replacement — Using resource files/DLLs with VB — Adding GZip to your projects
    Expect more to come in future
    If I have helped you, RATE ME! :-)

    I love helping noobs with their VB problems (probably because, as an amateur programmer, I am only slightly better at VB than them :-)) but if you SERIOUSLY want to get help for free from a community such as VBForums, you have to first have a grounding (basic knowledge) in VB6, otherwise you’re way too much work to help…You’ve got to give a little if you want to get help from us, in other words!

    And we DON’T do your homework. If your tutor doesn’t teach you enough to help you make the project without his or her help, FIND A BETTER TUTOR or try reading books on programming! We are happy to help with minor things regarding the project, but you have to understand the rest of it if you want our help to be useful.


  7. Nov 2nd, 2006, 10:31 PM


    #7

    Re: Create and Save file in Memory

    The idea behind is to keep the file in the memory and avoid the user from editing it.only my program has to acces the file, and after modification i will save the file in a physical path with encryption.

    Is there any method avaliable to keep the file in the memory.The file types are
    text,xml,html and word docuemts


  8. Nov 2nd, 2006, 10:35 PM


    #8

    Re: Create and Save file in Memory

    You’re still not giving the info we need! If only one program requires access to it, WHY even have a file and why not store it as data in a string or array…*that* is stored in memory.

    You’ve not told us anything of use yet…like how you intend to access the file, where it’ll be used, how many programs will need it, etc.

    Well, everyone else has been doing it :-)
    Loading a file into memory QUICKLY — Using SendKeys — HyperLabel — A highly customisable label replacement — Using resource files/DLLs with VB — Adding GZip to your projects
    Expect more to come in future
    If I have helped you, RATE ME! :-)

    I love helping noobs with their VB problems (probably because, as an amateur programmer, I am only slightly better at VB than them :-)) but if you SERIOUSLY want to get help for free from a community such as VBForums, you have to first have a grounding (basic knowledge) in VB6, otherwise you’re way too much work to help…You’ve got to give a little if you want to get help from us, in other words!

    And we DON’T do your homework. If your tutor doesn’t teach you enough to help you make the project without his or her help, FIND A BETTER TUTOR or try reading books on programming! We are happy to help with minor things regarding the project, but you have to understand the rest of it if you want our help to be useful.


  9. Nov 2nd, 2006, 10:41 PM


    #9

    Re: Create and Save file in Memory

    Only my program wiil access it .Any I have already mentioned the file types are
    text,html,word and xml.Only I will create and accees the files.The file size may range from 1 mb to 5 mb.


  10. Nov 2nd, 2006, 10:54 PM


    #10


    Hyperactive Member


    Re: Create and Save file in Memory

    do you mean you want your program to only access the file, and say if some other program wants to edit the file while your program is running it will not allow it to open it is that what you mean or i chould be wrong.

    here a bit of code you can use to open the file in read lock mode.

    Code:

    Dim FilePtr As Long
    
    Private Sub Command1_Click()
        FilePtr = FreeFile
        Open "C:\test.txt" For Binary Lock Read As #FilePtr
        'write what ever code here to deal with file editing
        
    End Sub
    
    Private Sub Command2_Click()
        Close #FilePtr
    End Sub

    what the code will do is when you click Command1 and that you got a text file in c:\test.txt will open the file, so you can edit etc

    but if you try to access it with some other program eg notepad you just get a message like «The process cannot access the file because it is being used by another process.»

    you also get it if you try to move or copy the file, tho only works while your program still has the file open. untill it closes it , witch then you can do your encryption whatever.

    When your dreams come true.
    On error resume pulling hair out.


  11. Nov 2nd, 2006, 11:04 PM


    #11

    Re: Create and Save file in Memory

    Thanks for the reply.
    I will open the file with this
    x=Shell(«Notepad C:\test.txt»)
    Now i want to allow the user to edit the contents with this shelled part only.I want to restrict the user from opening from other note pad.How can I?


  12. Nov 3rd, 2006, 12:42 AM


    #12

    Re: Create and Save file in Memory

    you could create a ram disk then use that for your working area, which will remain after your program close, until you shut down, but a ram disk is still available to other users. but if you are opening/ creating a word document, you can make an instance of word as visible = false text files and html can be stored as a string, and accessed in memory for reading /editing, but unless saved are not available after the program closes, xml files depend how you want to access them

    also you can set the file attributes of the notepad file to hidden readonly system etc after you open your copy, or just plain delete it and save it again afterwards, but in event of power off it is gone

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Create and Save file in Memory

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

NETWORK ADMINISTRATIONSWindows server


Alice AUSTIN

How to create a file in memory in Windows Server? Helpful? Please support me on Patreon: https://www.patreon.com/roelvandepaar With thanks & praise to God …

source

windows server

  • DevOps & SysAdmins: SSL for OpenLDAP on Centos 7 not working (2 Solutions!!)
  • Division2 DZ みんなのうた [ディビジョン2 PVP/PVE]

Alice AUSTIN

Alice AUSTIN is studying Cisco Systems Engineering. He has passion with both hardware and software and writes articles and reviews for many IT websites.

You May Also Like

Servidor web com Ubuntu #1 – Instalação e otimização do SO


Veloren – Exploring this Free RPG! – Open Source & Linux (Q&A) – (Minecraft / Cube World)


Microsoft Server Down, Airtel Copying Jio Again, FBI Unlock Samsung Phone, Fake IRCTC Refund Website


Alice AUSTIN

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment *

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Почему не открывается мой компьютер на windows 10
  • Активация windows 10 pro командная строка
  • Windows 10 tablet mode off
  • Программа для смены загрузочного экрана windows 7
  • Что выбрать в биос при установке с флешки windows