文件操作之函数调用的文件内容拷贝(非文件流)

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

#define LEN 30
#define BUF_SIZE 1024

int main(){

	int state1;
	int state2;
	int fp1,fp2;
	int len,sourceLen,destLen;
	char buf[BUF_SIZE];
	char source[LEN],dest[LEN];

//open
	printf("input path of source file:\n");
	scanf("%s",source);
	printf("input path of destination file:\n");
	scanf("%s",dest);
	printf("cource:%s\n",source);
	printf("dest:%s\n",dest);

	fp1 = open(source,O_RDONLY);
	if(fp1 == -1){
		printf("fail to open file!\n");
		exit(1);
	}

	fp2 = open(dest,O_WRONLY|O_CREAT,0755);
		if(fp2 == -1){
			printf("fail to open file!\n");
			exit(1);
		}
		sourceLen = lseek(fp1,0,SEEK_END);        //获取fp1文件的所以内容字节数
		lseek(fp1,0,SEEK_SET);                    //把读写位置移动到开头

	//write something
	while(1){
		 len = read(fp1,buf,sizeof(buf)); //获取fp2文件的sizeof(buf)字节数,与实际的len个字节对比
		 write(fp2,buf,len);                          //写进len个字节到fp2
		 if(len < BUF_SIZE){  //内容少于等于sizeof(buf) 循环一次 否则继续读写 直到文件内容全部拷贝完成
			 break;
		 }
	}

		destLen = lseek(fp2,0,SEEK_END);      //全部拷贝之后 fp1,fp2的所以内容大小相等,则复制成功
		if(sourceLen == destLen){
			printf("copy successful!\n");
		}else{
			printf("source len:%d,dest len:%d\n",sourceLen,destLen);
		}
	//close
	state1 = close(fp1);
	if(fp1 == 0){
		printf("close successful!\n");
	}else if(fp1 == -1){
		printf("Erreo:%s,errno:%d\n",strerror(errno),errno);
	}
	state2 = close(fp2);
		if(fp2 == 0){
			printf("close successful!\n");
		}else if(fp2 == -1){
			printf("Erreo:%s,errno:%d\n",strerror(errno),errno);
		}
	return 0;
}

*注意:这里的source和dest为具体的文件位置,写绝对路径。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值