title: How to display contents of a file using command line arguments in C?
body: <p>I came across a question to copy contents from one file to another using command line arguments in C. It is as follows:</p>
  
  <p>Q: Write a C program to copy contents of one file to another using command line arguments in C. The following output should be obtained:</p>
  
  <pre><code>1) &gt;&gt;&gt; ./a.out
       Display: "Insufficient arguments"
  
  2) &gt;&gt;&gt; ./a.out a.txt b.txt
       Display: File not created
  
  3) &gt;&gt;&gt; ./a.out a.txt b.txt
       Display: File is empty
  
  4) &gt;&gt;&gt; ./a.out a.txt b.txt     
       Display: File successfully copied
  5) &gt;&gt;&gt; b.txt
       Display: Hello World.
  </code></pre>
  
  <p>The code that I have written for the above question is:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  main(int argc,char *argv[])
  {
   FILE *fp1,*fp2;
   char ch;
   if(argc!=3)
   {
    printf("\n insufficient arguments.\n");
    exit(0);
   }
   fp1=fopen(argv[1],"r");
   fp2=fopen(argv[2],"w");
   if(fp1==NULL || fp2==NULL)
   {
     printf("\n File not created.\n");
     exit(0); 
   }
   if (NULL != fp1) 
   {
      fseek (fp1, 0, SEEK_END);
      int size = ftell(fp1);
      if (0 == size)
      {
       printf("File is empty.\n");
       exit(0);
      }
   }
  while(!feof(fp1))
  {
   ch=fgetc(fp1);
   fputc(ch,fp2);
  }
  printf("\n File successfully copied ");
  fclose(fp1);
  fclose(fp2);
  }
  </code></pre>
  
  <p>When I run the above code I get the output as:</p>
  
  <pre><code>   sh-4.2$ gcc main.c
     sh-4.2$ ./a.out
  
     Insufficient arguments.
  
     sh-4.2$ gcc main.c
     sh-4.2$ ./a.out a.txt b.txt
  
     File not created.
  
     sh-4.2$ gcc main.c
     sh-4.2$ ./a.out a.txt b.txt    // I created one empty file a.txt 
  
     File is empty. 
  
     sh-4.2$ gcc main.c                                         
     sh-4.2$ ./a.out a.txt b.txt   // Saved "Hello World" to a.txt and created empty file b.txt
  
     File successfully copied
  
     sh-4.2$ gcc main.c
     sh-4.2$ b.txt                // Why can't I carry out this operation as given in question?
     sh: ./b.txt: Permission denied
  
     sh-4.2$ gcc main.c
     sh-4.2$ cat b.txt
     � 
     sh-4.2$ cat a.txt
     Hello World
  </code></pre>
  
  <p>I got this symbol: � when I tried to display contents of b.txt. But when I displayed contents of a.txt I got Hello World. I couldn't display contents of b.txt by simply typing its name as given in the question. It came only after I included 'cat' command before the file name.</p>
  
  <p>I would like to solve the problem in the most simplest way possible. Have I missed any logic or any line in the code?</p>