Skip to content

Instantly share code, notes, and snippets.

@reu
Created June 12, 2010 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/435769 to your computer and use it in GitHub Desktop.
Save reu/435769 to your computer and use it in GitHub Desktop.
Simple file copy example using functions
#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