/* A simple C program that demonstrates how to do simple I/O in C, using the scanf and printf functions. This program allows the user to make a copy of a file. It prompts the user for the names of the original and duplicate files, and opens them. It uses a loop to read individual characters from the first file and then writes them to the second. Author: Krishnan Pillaipakkamnatt */ /* Include standard headers. Vaguely similar to import statement in Java.*/ #include /* Program execution begins in the main function. */ int main() { char next_char; /* To hold input characters */ int char_count; /* Counts characters copied. */ char in_name[256], /* char arrays are treated as strings. Here, */ out_name[256];/* in_name is for the name of input file, */ /* out_name is for the output file. */ FILE *fin, *fout; /* FILE pointers (handles) */ /* Use printf to print messages to standard output: */ printf("The super-D-duper file copying program.\n"); printf("Please input source file name: "); /* Use scanf to input data from standard input. */ scanf("%s", in_name); printf("Please input destination file name: "); scanf("%s", out_name); /* Attempt to open files. */ fin = fopen(in_name, "r"); if ( fin == NULL ) { printf("Error. The file '%s' cannot be read. Exiting.\n"); exit(1); } fout = fopen(out_name, "w"); if ( fout == NULL ) { printf("Error. The file '%s' cannot be written. Exiting.\n"); exit(1); } char_count = 0; /* Use fscanf to read from input file. */ while ( fscanf(fin, "%c", &next_char) != EOF ){ /* Use fprint to print to output file. */ fprintf(fout, "%c", next_char); char_count = char_count + 1; } /* We're done, close files. */ fclose(fout); fclose(fin); printf("Copied %d chars.\n", char_count); /* Time to close shop. */ exit(0); }