Enhanced Copy Command

Write a program to implement the copy(cp) command of Linux OS.
Copy the file to another file. If another file with the same name is already present in the current directory, ask for overwriting, if the user agrees then replace the file.

#include<stdio.h>
int main(int argc,char**argv)
{
	FILE *fp1,*fp2;
	char op;
	if(argc != 3)
	{
		printf("Usage:./a.out filename filename\n");
		return 0;
	}
	fp1 = fopen(argv[1],"r");
	if(fp1 == NULL)
	{
		printf("File is not present in this directory\n");
		return 0;
	}
	fp2 = fopen(argv[2],"r");
	if(fp2 != NULL)
	{
		printf("Do you want to overwrite ? ");
		scanf(" %c",&op);
		if(op == 'n' || op == 'N')
		{
			return 0;
		}
		fclose(fp2);
	}
	fp2 = fopen(argv[2],"w");
	while((op = fgetc(fp1)) != EOF)
	{
		fputc(op,fp2);
	}
	fclose(fp1);
	fclose(fp2);
	return 0;
}

Note: File with name “data” is present is the current directory, which contains data “LotToLearn”.

cat data
LotToLearn

Output

./a.out
Usage:./a.out filename filename

We didn`t give valid input so the above line is showing how to use this command


./a.out data data2

The data file is copied, a new file is generated with name data2(same content as data).

cat data2
LotToLearn

./a.out data data2
Do you want to overwrite ? n

n is pressed, so it will not overwrite the current file.


./a.out data data2
Do you want to overwrite ? y

y is pressed, so it will overwrite the current file.


cat data
LotToLearn
cat data2
LotToLearn

Since I haven`t modified the data file, you didn`t see the change in the data2 file.