#include #include #include #include #include #include #include #define READBUFSIZE 1024 /* Copy a file one byte at a time */ int main(int argc, char **argv) { int fin, fout; char readbuf[READBUFSIZE]; // Take the filename and number of bytes from command line arguments if (argc != 3) { fprintf(stderr, "usage: ./cp_example outfile nBytes\n"); return EXIT_FAILURE; } // Open the input file fin = open("/dev/zero", O_RDONLY); if (fin == -1) { perror("open for read failed"); return EXIT_FAILURE; } // Open the output file fout = open(argv[1], O_WRONLY | O_CREAT); if (fout == -1) { perror("open for write failed"); return EXIT_FAILURE; } // Read number of bytes to transfer long nBytes; if ( sscanf(argv[2], "%ld", &nBytes) != 1 ) { fprintf(stderr, "Invalid number of bytes: %s\n", argv[2]); return EXIT_FAILURE; } // Read from the file, write to fout. size_t readLen = 0; int bytesRemaining = 0; for (bytesRemaining=nBytes; bytesRemaining>0; bytesRemaining -= readLen ) { size_t bytesToRead = READBUFSIZE < bytesRemaining ? READBUFSIZE : bytesRemaining; if ( (readLen = read(fin, readbuf, bytesToRead)) == 0) break; // EOF // Test to see if we encountered an error while reading. if ( readLen < 0 ) { if ( errno == EINTR ) { readLen = 0; // try again } else { perror("read failed"); return EXIT_FAILURE; } } if (write(fout, readbuf, readLen) < readLen) { perror("fwrite failed"); return EXIT_FAILURE; } } close(fin); close(fout); return EXIT_SUCCESS; }