read/writeシステムを使用してレプリケーションファイルを呼び出す

2755 ワード

//copy_system.c
 //NOTE: unistd.h header file should be included at first
// for other header files  would depend on it
#include 
#include 
#include 
#include 
#include 

//for files
#include 
#include 
#include 

#define  STD_FILE_INPUT		0
#define  STD_FILE_OUTPUT	1
#define  STD_FILE_ERROR		2

#define  EACH_UNIT 128

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

	const char *src_file = "./draft1.txt";
	const char *dest_file = "./draft2.txt";

	//open two files
	int fd_src = open(src_file, O_RDONLY);
	if(fd_src == -1){
		char err[128];
		sprintf(err, "open src file failed, errno = %d 
", errno); write(STD_FILE_OUTPUT, err, strlen(err)+1); return -1; } int fd_dest = open(dest_file, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR); if(fd_dest == -1){ char err[128]; sprintf(err, "open [O_WRONLY] dest file failed, errno = %d
", errno); write(STD_FILE_OUTPUT, err, strlen(err)+1); fd_dest = open(dest_file, O_CREAT, S_IWUSR | S_IRUSR); if(fd_dest == -1) { char err[128]; sprintf(err," create [ S_IWUSR | S_IRUSR] dest file failed, errno = %d
", errno); write(STD_FILE_OUTPUT, err, strlen(err)+1); close(fd_src); return -1; } } int nread = 1; while(nread){ char c ; //nread = read(fd_src, &c, sizeof(c)); char data[EACH_UNIT] = {0}; nread = read(fd_src, &data, sizeof(data)); if(-1 != nread){ //fd_src+=nread; printf("[while] - nread :%d
", nread ); // , //int nwrite = write(fd_dest, &c, nread); int nwrite = write(fd_dest, &data, nread); printf("[while] - nwrite :%d
", nwrite ); if(nwrite == -1){ const char * err_msg_write = "write error
"; write(STD_FILE_OUTPUT, err_msg_write, sizeof(err_msg_write)/ sizeof(err_msg_write[0])); close(fd_dest); close(fd_src); return -2; } //fd_dest+=nwrite; }else{ const char * err_msg_read = "read error
"; write(STD_FILE_OUTPUT, err_msg_read, sizeof(err_msg_read)/ sizeof(err_msg_read[0])); close(fd_dest); close(fd_src); return -3; } }//while //close both file handles close(fd_dest); close(fd_src); return 0; } /* [queyue@localhost file-system]$ TIMEFORMAT="" time ./test-copy-system [while] - nread :128 [while] - nwrite :128 [while] - nread :14 [while] - nwrite :14 [while] - nread :0 [while] - nwrite :0 0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 432maxresident)k 0inputs+0outputs (0major+141minor)pagefaults 0swaps */