logoISU  

CS 456 - Systems Programming

Spring 2024

Displaying ./code/feb01/mycopy.c

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>

#define K 1024

int main (int argc, char **argv){

	if (argc < 3){
	   fprintf(stderr, "Usage %s source destination\n",argv[0]);
	   exit(1);
	}

	//char data[K];
	int rt;

	//open a file
	int src = open(argv[1], O_RDONLY);

	if(src == -1){
		write(2, "open failed\n",12);
		return -1;
	}

	int size;
	struct stat st;
	fstat(src, &st);
	size = st.st_size;

	int dst = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0666);

	char buf[size+1];

	rt = read(src, buf, size);

	//printf("Number of bytes read: %d\n", rt);

	write(dst, buf, rt);

	close(src);
	close(dst);
	
	return 0;

}