Hi guys,

Today, I am going to share a small utility that I created when I was in college. Yeah! It’s something like old school stuff! But it was fun.

Copying a file to one location to another using C Language. It is same as cp shell command. I hope that it will help college guys or freshers who are working in C.

Here is the code: copy.c

#define BUFSIZE 1024
#include <fcntl.h>
#include <sys/stat.h>

int main(int argc, char**argv) {
	int fd1, fd2, n;
	char buf[BUFSIZE];

	if(argc != 3) {
		printf("\n In CP command : Too few or Bad arguments ");
		printf("\n USAGE: copy <source> <destination>");
		return(0);
	}
	if((fd1 = open(argv[1], O_RDONLY)) == -1) {
		printf("\n In CP command : Error opening Source File");
		return(-1);
	}
	if((fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH)) == -1) {	//Mode 664
		printf("\n In CP command : Error opening Destination File");
		return(-1);
	}

	while((n=read(fd1, buf, BUFSIZE)) > 0) {
		write(fd2, buf, n);
	}
	close(fd1);
	close(fd2);
	return(0);
}

Compile it:

gcc copy.c

You will see that a compiled file “a.out” is generated in the same directory.

To run it:

./a.out "source-file" "destination-file"

For example,

./a.out /home/user/test.c /home/user/codes/newtest.c

 

That’s it guys. Have fun!

Critics/suggestion are very much welcome.

Have a nice day ahead.

Loading