#include // so I can do reasonable i/o #include // open at least #include // open #include // open #include // read #include // strcmp #include // perror #include using namespace std; void Usage(char * progname) { cerr << "\tUsage " << progname << " sides" << endl; cerr << "\t sides must be positive " << endl; } int main( int argc, char * argv[]) { int sides = 6; srand(time(nullptr)); if (argc != 2) { Usage(argv[0]); } else { sides = atoi(argv[1]); if (sides < 1) { Usage(argv[0]); sides = 6; } } int theFD, openFlags {O_CREAT | O_RDWR | O_TRUNC}; mode_t filePerms{ filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH}; theFD = open("diceFile", openFlags, filePerms); if (theFD == -1){ perror("Could not open the output file "); return 1; } int tmp{0}; int count; for(int i = 0; i < sides; ++i) { write(theFD, &tmp, sizeof(int)); } for(int i = 0; i < 1'000; ++i) { tmp = static_cast(rand() % sides); lseek(theFD, tmp*sizeof(int), SEEK_SET); read(theFD, &count, sizeof(int)); ++count; lseek(theFD, -1*sizeof(int), SEEK_CUR); write(theFD, &count, sizeof(int)); cout << tmp << " " << count << endl; } cout << endl << endl; lseek(theFD, 0, SEEK_SET); for(int i = 0; i < sides ; ++i) { read(theFD, &count, sizeof(int)); cout << setw(10) << i << setw(20) << count << endl; } return 0; }