【问题标题】:how do I copy the contents of a file into virtual memory?如何将文件的内容复制到虚拟内存中?
【发布时间】:2011-08-12 07:09:58
【问题描述】:

我有一个小文件,我查看它并计算其中的字节数:

while(fgetc(myFilePtr) != EOF)
{

   numbdrOfBytes++;

}

现在我分配相同大小的虚拟内存:

BYTE* myBuf = (BYTE*)VirtualAlloc(NULL, numbdrOfBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

我现在想将我的文件内容复制到 nyBuf。我该怎么做?

谢谢!

【问题讨论】:

  • 在 Linux 上,有一个很好的系统调用 mmap 可以为您完成这项工作,而无需专门分配内存。 Windows 可能有类似的东西。
  • 获取文件大小,可以:fseek(fp, 0L, SEEK_END); long size = ftell(fp); rewind(fp);

标签: c++ windows operating-system virtualalloc


【解决方案1】:

试试这个:

#include <fstream>
#include <sstream>
#include <vector>

int readFile(std::vector<char>& buffer)
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         *
         * Then read the whole file into the buffer.
         */
        buffer.resize(length);
        file.read(&buffer[0],length);
    }
}

【讨论】:

    【解决方案2】:

    也可以考虑改用memory mapped files

    【讨论】:

      【解决方案3】:

      大纲:

      FILE * f = fopen( "myfile", "r" );
      fread( myBuf, numberOfBytes, 1, f );
      

      这假设缓冲区足够大以容纳文件的内容。

      【讨论】:

        猜你喜欢
        • 2015-03-29
        • 2014-12-16
        • 2020-02-11
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 1970-01-01
        • 2021-09-22
        • 2011-05-23
        相关资源
        最近更新 更多