Header Ads

29 - WAP to Concatinnate 2 Files using Command Line Arguments in C

This Program enables the user to Concatinnate 2 files into 1 from Command Line Arguments in C.

Program Code :

//program to copy 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
 //declaring file pointers and other variables
 FILE *fp1, *fp2, *fp3;
 int var;
 char buff[100];
 
 //if there was no file
 if (argc == 1)
 {
  //Reading from stdin and saving in a buffer
  fscanf(stdin, "%[^\n]", buff);

  //printing from buffer
  fprintf(stdout, "%s\n", buff);
 }

 //if there is only one file
 else if (argc == 2)
 {
  //opening the file in read mode
  fp1 = fopen(argv[1], "r");
  
  //checking the file if it contains any thing or not
  if (fp1 == NULL)
  {
   fprintf(stderr, "%s", "no file present\n");
   exit(1);
  }

  //this loop will display all the contents of file
  while ((var = fread(buff, 1, sizeof (buff),fp1)) != '\0')
  {
   fwrite(buff, 1, sizeof (buff), stdout);
  }
 }

 //if user enters only two files
 else if (argc == 3)
 {
  //opening file 1
  fp1 = fopen(argv[1], "r");
  
  //
  if (fp1 == NULL)
  {
   fprintf(stderr, "%s", "File 1 Missing\n");
   exit(1);
  }

  //loop to copy the contents in buffer and displaying from buffer on stdout
  while (var = fread(buff, 1, sizeof (buff), fp1))
  {
   fwrite(buff, 1, sizeof (buff), stdout);
  }
 
  //continuing the same thing for the second file
  fp2 = fopen(argv[2], "r");
  
  if (fp2 == NULL)
  {
   fprintf(stderr, "%s", "File 2 Missing\n");
   exit(1);
  }
 
  while (var = fread(buff, 1, sizeof (buff), fp2))
  {
   fwrite(buff, 1, sizeof (buff), stdout);
  }
 }
 
 //if user enters  3 files
 else if (argc == 4)
 {
  //creating a new 3rd file
  fp3 = fopen(argv[3], "a+");
  
  //opening first file
  fp1 = fopen(argv[1], "r");
  
  //checking the file
  if (fp1 == NULL)
  {
   fprintf(stderr, "%s", "File 1 Missing\n");
   exit(1);
  }

  //copying the contents from file 1 to file 3
  while (var = fread(buff, 1, sizeof (buff), fp1))
  {
   fwrite(buff, 1, var, fp3);
  }
 
  //repeating the same for file 2
  fp2 = fopen(argv[2], "r");
  
  if (fp2 == NULL)
  {
   fprintf(stderr, "%s", "File 2 Missing\n");
   exit(1);
  }
 
  while (var = fread(buff, 1, sizeof (buff), fp2))
  {
   fwrite(buff, 1, var, fp3);
  }
 }
 return 0;
}

Program Output:

./a.out  <filename1>  <filename2>  <filename3>    
The Contents of Filename1 & Filename2 is merged within the filename3

No comments