#include #include #include #define READBUFSIZE 1024 /* Copy a file one byte at a time */ int main(int argc, char **argv) { FILE *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 = fopen("/dev/zero", "rb"); // "rb" --> read, binary mode if (fin == NULL) { perror("fopen for read failed"); return EXIT_FAILURE; } // Open the output file fout = fopen(argv[1], "wb"); // "wb" --> truncate & write, binary mode if (fout == NULL) { perror("fopen 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 = fread(readbuf, 1, bytesToRead, fin)) == 0) break; if (fwrite(readbuf, 1, readLen, fout) < readLen) { perror("fwrite failed"); return EXIT_FAILURE; } } // Test to see if we encountered an error while reading. if (ferror(fin)) { perror("fread failed"); return EXIT_FAILURE; } fclose(fin); fclose(fout); return EXIT_SUCCESS; }