In: Computer Science
Solution
Code 1 - The code has been given below along with the output. Comments have been placed to depict the functionality.
#include <stdio.h>
int main()
{
/*Create File Pointers*/
FILE *fle, *flecopy;
char ch;
/*Open input file for reading */
fle = fopen("input.txt", "r") ;
/* open output file in writing mode, file will be created if not existing*/
flecopy = fopen("copied.txt","w");
/*Return message if there is a problem opening the file*/
if ( fle == NULL )
{
printf( "Error Opening the file" ) ;
}
else
{
while ( 1 )
{
/*Read file character by character*/
ch = fgetc ( fle ) ;
if ( ch == EOF )
break ;
/*Copy the character to the copied file*/
fputc(ch,flecopy) ;
}
/*Close the files*/
fclose (fle ) ;
fclose (flecopy);
}
return 1;
}
Output:
input.txt = "This is the input file, its contents are to be copied."
copied.txt = Not existing before the program run.
copied.txt (after
program run) = "This is the input file, its contents are
to be copied."
Code 2 : Modified code where file names are given by the user.
#include <stdio.h>
int main()
{
char inp[50],outp[50];
/*ask user for the file names */
printf("Enter the input file name : ");
scanf("%s",inp);
printf("Enter the file name to which contents are to be copied: ");
scanf("%s",outp);
/*Create File Pointers*/
FILE *fle, *flecopy;
char ch;
/*Open input file for reading */
fle = fopen(inp, "r") ;
/* open output file in writing mode, file will be created if not existing*/
flecopy = fopen(outp,"w");
/*Return message if there is a problem opening the file*/
if ( fle == NULL )
{
printf( "Error Opening the file" ) ;
}
else
{
while ( 1 )
{
/*Read file character by character*/
ch = fgetc ( fle ) ;
if ( ch == EOF )
break ;
/*Copy the character to the copied file*/
fputc(ch,flecopy) ;
}
/*Close the files*/
fclose (fle ) ;
fclose (flecopy);
}
return 1;
}
Ouput:
Enter the input file name :
input.txt
Enter the file name to which contents are to be copied:
newcopiedfile.txt
After the program runs the contents of the newcopiedfile.txt
"This is the input file, its contents are to be copied."