Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2017
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <sys/mman.h> // for mmap
  3. #include <fcntl.h> // for O_RDWR
  4. #include <unistd.h> // for close(fd)
  5. using std::cout;
  6. using std::endl;
  7. using std::cin;
  8. int validNumberToAdd()
  9. {
  10.     cout << "valid numbers are 0-10000" <<endl;
  11.     int res;
  12.     cin >> res;
  13.     if(res <0 || res > 10000)
  14.     {
  15.         validNumberToAdd();
  16.     }
  17.     else
  18.     {
  19.         return res;
  20.     }
  21. }
  22. int validIndex()
  23. {
  24.     cout << "What index do you want to look for 0-99? " << endl;
  25.     int res;
  26.     cin >> res;
  27.     if(res < 0 || res > 99)
  28.     {
  29.         cout << "invalid selection pick between 0-99" << endl;
  30.         validIndex();
  31.     }
  32.     else
  33.     {
  34.         return res;
  35.     }
  36. }
  37. void readFile()
  38. {
  39.     const char * filePath = "num.txt";
  40.     int index;
  41.     index = validIndex();
  42.  
  43.     int fd = open(filePath,O_RDONLY );
  44.     void *addr = mmap(nullptr,1000,PROT_READ, MAP_SHARED , fd,0);
  45.     char *p = (char *)addr;
  46.     cout << p[index] << endl;
  47.     close(fd);
  48. }
  49. void writeFile()
  50. {
  51.     const char * filePath = "numbers.txt";
  52.     int fd = open(filePath,O_RDWR);
  53.     int index,numAdd;
  54.     index = validIndex();
  55.     numAdd = validNumberToAdd();
  56.     void *addr = mmap(nullptr,1000,PROT_WRITE, MAP_SHARED| MAP_ANONYMOUS, fd,0);
  57.     char *p = (char *)addr;
  58.     p[index] = numAdd;
  59.     cout << "wrote " << numAdd << endl;
  60.     //munmap(addr,1000);
  61.     close(fd);
  62.  
  63. }
  64. void menu()
  65. {
  66.     cout << "Type 'r' to read" << endl;
  67.     cout << "Type 'w' to write" << endl;
  68.     cout << "Type 'q' to quit" << endl;
  69.     char res;
  70.     cin >> res;
  71.     if(res != 'r' && res != 'w' && res != 'q')
  72.     {
  73.         cout << " Your selection was invalid " << res << " is not valid" << endl;
  74.         menu();
  75.     }
  76.     if(res == 'r')
  77.     {
  78.         readFile();
  79.         menu();
  80.     }
  81.     if(res == 'w')
  82.     {
  83.         writeFile();
  84.         menu();
  85.     }
  86.     if(res == 'q')
  87.     {
  88.         cout << "Exiting program!" << endl;
  89.         exit(1);
  90.     }
  91. }
  92. int main()
  93. {
  94.     menu();
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement