Last active
December 26, 2015 06:49
-
-
Save chihuahua/7110029 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Makes a copy of a file. | |
| * The destination file name must not already exist. | |
| * Usage: ./executable source destination | |
| * @author Chi Zeng ([email protected]) and section-mates | |
| * Oct. 22, 2013 | |
| */ | |
| #include <stdio.h> | |
| int main(int argc, char* argv[]) | |
| { | |
| if (argc != 3) | |
| { | |
| // check for correct usage. | |
| printf("Usage: ./executable source destination"); | |
| return 1; | |
| } | |
| FILE* sourceFile = fopen(argv[1], "r"); | |
| if (!sourceFile) | |
| { | |
| // make sure the source file exists. | |
| printf("File %s does not exist.", argv[1]); | |
| return 1; | |
| } | |
| FILE* checkForDest = fopen(argv[2], "r"); | |
| if (checkForDest) { | |
| // if this file exists, yell at the user since we're overriding it. | |
| printf("Hey, %s exists!", argv[2]); | |
| return 1; | |
| } | |
| // close the read-only file we just made for checking. | |
| fclose(checkForDest); | |
| // open our destination file. create a new file if applicable. | |
| // possible override existing file. | |
| FILE* destFile = fopen(argv[2], "w"); | |
| // create a buffer to store data to be read in. | |
| int numBytesPerRead = 100; | |
| char buffer[numBytesPerRead]; | |
| int numBytesRead; | |
| do { | |
| // read a chunk of data from source file. | |
| numBytesRead = fread(buffer, 1, numBytesPerRead, sourceFile); | |
| // write that chunk of data to destination. | |
| // notice we only write the num. of bytes we actually read. | |
| // not the max. number of bytes we could've possibly read. | |
| fwrite(buffer, numBytesRead, 1, destFile); | |
| } while (numBytesRead == numBytesPerRead); | |
| // close our files. | |
| fclose(sourceFile); | |
| fclose(destFile); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment