Loading your workspace…
Loading your workspace…
Read a source file name and a target file name, copy the source file character by character into the target, and report errors when a file cannot be opened.
This program opens real files on the machine that runs it. The online Run button uses a remote sandbox without your local files, so the sample shows the error path for a missing file. To see the copy succeed, save the code locally, create a text file with some lines, and run the program with that file name.
#include <stdio.h>
int main(void) {
char source_name[100], target_name[100];
FILE *source, *target;
int ch;
printf("Enter source file name:\n");
scanf("%99s", source_name);
printf("Enter target file name:\n");
scanf("%99s", target_name);
source = fopen(source_name, "r");
if (source == NULL) {
printf("Error: cannot open source file %s\n", source_name);
return 1;
}
target = fopen(target_name, "w");
if (target == NULL) {
printf("Error: cannot create target file %s\n", target_name);
fclose(source);
return 1;
}
while ((ch = fgetc(source)) != EOF) {
fputc(ch, target);
}
fclose(source);
fclose(target);
printf("Copied %s to %s\n", source_name, target_name);
return 0;
}
Input
missing.txt
copy.txtOutput
Enter source file name:
Enter target file name:
Error: cannot open source file missing.txtfopen returns NULL when a file cannot be opened, so the program checks the result before it reads or writes anything. Each opened file is closed on every exit path so that no handle is left open.
fgetc returns an int, not a char, because EOF is a negative value that a char might not be able to hold on some platforms. Storing the result in an int keeps the end-of-file test reliable.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
missing.txt copy.txt
Expected output
Enter source file name: Enter target file name: Error: cannot open source file missing.txt
A pointer to a structure that holds the state of an open stream, such as the buffer and current position.
NULL, which is why the result must be checked.
fgetc reads one character from a file and returns it as an int; fputc writes one character to a file.
It flushes buffered output and releases the file handle, so the data is written completely.
A constant returned by the input functions when the end of the file has been reached or a read error occurred.
Back to all VTU BPOPS103 lab programs.