Created
June 12, 2010 14:17
-
-
Save reu/435769 to your computer and use it in GitHub Desktop.
Simple file copy example using functions
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
#include <stdio.h> | |
#include <stdlib.h> | |
int main(int argc, char *argv[]) | |
{ | |
return copy(open_file_for_reading(argv[1]), open_file_for_writing(argv[2])); | |
} | |
int copy(FILE *source_file, FILE *target_file) | |
{ | |
char current_char; | |
while(current_char != EOF){ | |
current_char = fgetc(source_file); | |
fputc(current_char, target_file); | |
} | |
return fclose(source_file) && fclose(target_file); | |
} | |
FILE *open_file_for_reading(char *file_name) | |
{ | |
FILE *file; | |
file = fopen(file_name, "r"); | |
if(!file){ | |
puts("Ops, source file not found"); | |
exit(EXIT_FAILURE); | |
} | |
return file; | |
} | |
FILE *open_file_for_writing(char *target_file_name) | |
{ | |
FILE *target_file; | |
target_file = fopen(target_file_name, "w"); | |
if(!target_file){ | |
puts("Ops, could allocate target_file"); | |
exit(EXIT_FAILURE); | |
} | |
return target_file; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment