#include // so I can do reasonable i/o #include // open at least #include // open #include // open #include // read #include // strcmp #include // perror const int BUFFER_SIZE = 1024; using namespace std; void Usage(char *); int main(int argc, char * argv[]) { int inputFD, outputFD, openFlags; mode_t filePerms; ssize_t numRead; char buf[BUFFER_SIZE]; if (argc != 3 || strcmp(argv[1],"--help") == 0) { Usage(argv[0]); } cout << "copying " << argv[1] << " to " << argv[2] << endl; // open the input file. inputFD = open(argv[1], O_RDONLY); if (inputFD == -1) { perror("Could not open the inputfile "); return 1; } // build the arguments to open the file. // a | b is the bitwise inclusive or of the two arguments. // 1001 | 1010 = 1011 // The constants are defined in the include files. // // create the file if it does not exits // open for write only // truncate the file if it does exist // This is standard ifstream.open() behavior openFlags = O_CREAT | O_WRONLY | O_TRUNC; // rw-rw-rw- filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; outputFD = open(argv[2], openFlags, filePerms); if (outputFD == -1){ perror("Could not open the output file "); return 1; } while((numRead = read(inputFD, buf, BUFFER_SIZE)) > 0) { if(write(outputFD, buf, numRead) != numRead) { perror("buffer write failed"); } } if (numRead == -1) { perror("A read failed"); return 1; } if(close(inputFD) == -1) { perror("Fail on closing input file"); return 1; } if (close(outputFD) == -1) { perror("Fail on closing output file"); return 1; } return 0; } void Usage(char * name) { cout << "Usage: " << name << " inputFile outputFile " << endl; return; }