Advertisement
zhangsongcui

file mapping 2

May 31st, 2012
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <boost/filesystem/v3/operations.hpp>
  4. #include <boost/interprocess/file_mapping.hpp>
  5. #include <boost/interprocess/mapped_region.hpp>
  6.  
  7. #include <boost/array.hpp>
  8. #include <fstream>
  9. #include <ctime>
  10.  
  11. struct random_generator {
  12.     random_generator() { std::srand((unsigned)std::time(NULL)); }
  13.  
  14.     char operator ()() {
  15.         int res = std::rand() % (26 + 26 + 10);
  16.         switch (res / 26) {
  17.         case 0:
  18.             return res + 'A';
  19.         case 1:
  20.             return res - 26 + 'a';
  21.         case 2:
  22.             return res - 26 * 2 + '0';
  23.         default:
  24.             return 0;
  25.         }
  26.     }
  27. };
  28.  
  29. int main()
  30. {
  31.     using namespace std;
  32.     using namespace boost;
  33.     const size_t filesize = (16 + 2) * 20000000;
  34.     {
  35.         // 生成一个指定大小的文件
  36.         ofstream fout("mapped_file.txt");
  37.         filesystem3::resize_file("mapped_file.txt", filesize);
  38.     }
  39.     {
  40.         interprocess::file_mapping mfile("mapped_file.txt", interprocess::read_write);
  41.         interprocess::mapped_region region(mfile, interprocess::read_write);
  42.         array<char, 18> * addr = (array<char, 18> *)region.get_address();
  43.         array<char, 18> * const end = addr + 20000000;
  44.         random_generator rg;
  45.         for (; addr != end; ++addr) {
  46.             generate_n(addr->begin(), 16, rg);
  47.             (*addr)[16] = '\r';
  48.             (*addr)[17] = '\n';
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement