/* Program to make a copy of an ASCII file. Asks user for filenames. */ #include #include FILE * open_user_file(char message[], char file_access_mode[]); main() { FILE *f_in, *f_out; int ch; /* Call our own function to query user for filename & open file. */ f_in = open_user_file("Copy which file?", "r"); /* Ditto for output */ f_out = open_user_file("Copy data to which file?", "w"); /* Now copy characters one at a time until end of file on input. */ ch = getc(f_in); while (ch != EOF) { putc(ch, f_out); ch = getc(f_in); } /* Now copied; close files. */ fclose(f_in); fclose(f_out); printf("File has been copied\n"); return 0; } /******* open_user_file ******* Prints the specified message, and reads a filename from the user. Then opens that file in the specified file access mode. If the open fails, the function stops the program with an error message. */ FILE * file_open(char name[], char access_mode[]); FILE * open_user_file(char message[], char file_access_mode[]) { char filename[81]; FILE *f; printf("%s ", message); scanf("%80s%*c", filename); f = file_open(filename, file_access_mode); return f; } FILE * file_open (char name[], char access_mode[]) { FILE * f; f = fopen (name, access_mode); if (f == NULL) { /* error? */ /* Library function perror prints an informative message. */ perror ("Cannot open file"); exit (1); /* Terminate after printing error message. */ } return f; /* Only happens if fopen succeeded. */ }