I came across a question to copy contents from one file to another using command line arguments in C. It is as follows:
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:
1) >>> ./a.out
Display: "Insufficient arguments"
2) >>> ./a.out a.txt b.txt
Display: File not created
3) >>> ./a.out a.txt b.txt
Display: File is empty
4) >>> ./a.out a.txt b.txt
Display: File successfully copied
5) >>> b.txt
Display: Hello World.
The code that I have written for the above question is:
#include<stdio.h>
#include<stdlib.h>
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);
}
When I run the above code I get the output as:
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
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.
I would like to solve the problem in the most simplest way possible. Have I missed any logic or any line in the code?