Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sys/mman.h> // for mmap
- #include <fcntl.h> // for O_RDWR
- #include <unistd.h> // for close(fd)
- using std::cout;
- using std::endl;
- using std::cin;
- int validNumberToAdd()
- {
- cout << "valid numbers are 0-10000" <<endl;
- int res;
- cin >> res;
- if(res <0 || res > 10000)
- {
- validNumberToAdd();
- }
- else
- {
- return res;
- }
- }
- int validIndex()
- {
- cout << "What index do you want to look for 0-99? " << endl;
- int res;
- cin >> res;
- if(res < 0 || res > 99)
- {
- cout << "invalid selection pick between 0-99" << endl;
- validIndex();
- }
- else
- {
- return res;
- }
- }
- void readFile()
- {
- const char * filePath = "num.txt";
- int index;
- index = validIndex();
- int fd = open(filePath,O_RDONLY );
- void *addr = mmap(nullptr,1000,PROT_READ, MAP_SHARED , fd,0);
- char *p = (char *)addr;
- cout << p[index] << endl;
- close(fd);
- }
- void writeFile()
- {
- const char * filePath = "numbers.txt";
- int fd = open(filePath,O_RDWR);
- int index,numAdd;
- index = validIndex();
- numAdd = validNumberToAdd();
- void *addr = mmap(nullptr,1000,PROT_WRITE, MAP_SHARED| MAP_ANONYMOUS, fd,0);
- char *p = (char *)addr;
- p[index] = numAdd;
- cout << "wrote " << numAdd << endl;
- //munmap(addr,1000);
- close(fd);
- }
- void menu()
- {
- cout << "Type 'r' to read" << endl;
- cout << "Type 'w' to write" << endl;
- cout << "Type 'q' to quit" << endl;
- char res;
- cin >> res;
- if(res != 'r' && res != 'w' && res != 'q')
- {
- cout << " Your selection was invalid " << res << " is not valid" << endl;
- menu();
- }
- if(res == 'r')
- {
- readFile();
- menu();
- }
- if(res == 'w')
- {
- writeFile();
- menu();
- }
- if(res == 'q')
- {
- cout << "Exiting program!" << endl;
- exit(1);
- }
- }
- int main()
- {
- menu();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement