Linux C编程连载(1)-cp的实现

【代码清单】

/**********************************************************
 * This program is use to copy src_file to dest_file
 * 1 Execute gcc -o copy copy.c
 * 2 then, copy the execute file "copy" to the /usr/bin
 * You can use command like this : copy src_file dest_file
 * Author : Tan De
 * Time   : 2011-04-04
 *********************************************************/

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

#define BUFF_SIZE 1024

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

	int src_file,dest_file;
	int real_read_len;
	unsigned char buff[BUFF_SIZE];

	//argc is not correct
	if(argc!=3){
	printf("Error use copy!\n");
	printf("Example:\n");
	printf("copy src_file dest_file\n");
	exit(1);	
	}

	//Open src_file read only
	src_file=open(argv[1],O_RDONLY);
	//If the dest_file is not exsit, then create new one
	dest_file=open(argv[2],O_WRONLY|O_CREAT,666);
	//Open error
	if(src_file<0||dest_file<0){
	printf("Open file error\n");
	printf("Can't copy!\n");
	printf("Please check cmd : copy src_file dest_file\n");
	exit(1);
	}

	//Copy src_file to dest_file
	while((real_read_len=read(src_file,buff,sizeof(buff)))>0){
	write(dest_file,buff,real_read_len);
	}

	//close fd
	close(dest_file);
	close(src_file);

	return 0;
}


 

转载请标明出处,仅供学习交流,勿用于商业目的

Copyright @ http://blog.csdn.net/tandesir

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值