Programming in C

(Barry) #1

366 Chapter 16 Input and Output Operations in C


With the functions fopen,putc,getc,and fclose,you can now proceed to write a
program that will copy one file to another. Program 16.3 prompts the user for the name
of the file to be copied and the name of the resultant copied file.This program is based
upon Program 16.2.You might want to refer to that program for comparison purposes.
Assume that the following three lines of text have been previously typed into the file
copyme:
This is a test of the file copy program
that we have just developed using the
fopen, fclose, getc, and putc functions.

Program 16.3 Copying Files
// Program to copy one file to another

#include <stdio.h>

int main (void)
{
char inName[64], outName[64];
FILE *in, *out;
int c;

// get file names from user

printf ("Enter name of file to be copied: ");
scanf ("%63s", inName);
printf ("Enter name of output file: ");
scanf ("%63s", outName);

// open input and output files

if ( (in = fopen (inName, "r")) == NULL ) {
printf ("Can't open %s for reading.\n", inName);
return 1;
}

if ( (out = fopen (outName, "w")) == NULL ) {
printf ("Can't open %s for writing.\n", outName);
return 2;
}

// copy in to out
Free download pdf