简体   繁体   中英

Write allocated memory to disk

I have an allocated memory and I want to write it to a file. How can I do that in C++ 20?

I know I could do the following sequence, just like in C. However, in C++ there is the std::filesystem , can't I do that with it?

  • CreateFile
  • VirtualAlloc
  • memcpy
  • WriteFile
  • VirtualFree
  • CloseHandle
auto* const data = VirtualAlloc(nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

if (!data)
    return 0;
    
memcpy(...);

if (data)
    VirtualFree(data, 0, MEM_RELEASE);

Here is the tried and true method for writing memory to a file:

// Open your output_file as binary
static const size_t DATA_CAPACITY = 0x1000;
output_file.write(data, DATA_CAPACITY);

This is known as block writing to a binary file (or a file in binary mode).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM