Write a program to print 1 20 in an output file out txt Each
Solution
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include <stdio.h>
 #include <stdlib.h>
 
 int main()
 {
 FILE *fs1, *fs2, *ft;
 
 char ch;
 
 fs1 = fopen(\"leapyear.txt\",\"r\"); //open file leapyear.txt in read mode
 fs2 = fopen(\"notleapyear.txt\",\"r\"); //open file notleapyear.txt in read mode
 
 if( fs1 == NULL) { //print error and exit if leapyear.txt is cannot be opened
 printf(\"Unable to open file leapyear.txt\ \");
 return 0;
 }
 
 if( fs2 == NULL) { //print error and exit if notleapyear.txt is cannot be opened
 printf(\"Unable to open file notleapyear.txt\ \");
 return 0;
 }
 
 
 
 ft = fopen(\"year.txt\",\"w\"); //open file year.txt in write mode
if( ft == NULL) { //print error and exit if year.txt is cannot be created in write mode
 printf(\"Error while creating file year.txt for writing.\ \");
 return 0;
 }
 
 while( ( ch = fgetc(fs1) ) != EOF ) //get each char from first file and put(write) to new file
 fputc(ch,ft);
 
 while( ( ch = fgetc(fs2) ) != EOF ) //get each char from second file and put(write) to new file
 fputc(ch,ft);
 
 printf(\"Two files were merged into year.txt file successfully.\ \");
 
 fclose(fs1); //close all opened files
 fclose(fs2);
 fclose(ft);
 
 return 0;
 }
--------------------------------------------
OUTPUT:
sh-4.3$ cat lsh-4.3$ cat leapyear.txt   
 1990   
 2000   
sh-4.3$ cat notleapyear.txt
 2003   
 2005   
 
 sh-4.3$ main   
 Two files were merged into year.txt file successfully.   
   
   
 sh-4.3$ cat year.txt   
 1990   
 2000   
 2003   
 2005   


