In: Computer Science
Write in C
We are interested in the implementation of a Unix/Linux system utility for the concatenation of a list of n text files. In order to do that we are going to consider the following syntax below where the concatenation of n text files are written in the output file all.txt or on the console if the output text file is not specified.
$./mycat file_1.txt file_2.txt . . . file_n.txt > all.txt
C code for above problem
#include
#include
int main(int argc,char **argv)
{
   int found=0;
   for(int i=1;i<argc;i++)
   {
       if(strcmp(argv[i],">")==0 && i==argc-2)
       {
           found=1;
           break;
       }
   }
  
   FILE *fout=NULL;
   if(found)
   {
       fout=fopen(argv[argc-1],"w");
       argc-=2;
   }
   for(int i=1;i<argc;i++)
   {
       FILE *fp=fopen(argv[i],"r");
       if(fp)
       {
           char line[100];
           while(fgets(line,sizeof(line),fp))
           {
               if(found)
               {
                   fprintf(fout,"%s",line);
               }
               else
               {
                   printf("%s",line);
               }
           }
       }
       fclose(fp);
   }
  
   if(found)
   {
       fclose(fout);
   }
   return 0;
}
Sample output
if "file_1.txt" has following data
My data of file-1
"file_2.txt" has following data
My data of file-2
(1):
If our command while running is "./a.out file_1.txt file_2.txt", then output looks as follows: (It means printing data of all files on console)

(2):
If our command while running is "./a.out file_1.txt file_2.txt > all.txt", then "all.txt" looks as follows: (It means writing all files into one file)
My data of file-1
My data of file-2