linux文件读写实战(cp指令的实现) 上

1.linux实现cp指令

函数原型

int      open(const char *pathname, int flags, mode_t mode);
ssize_t  read(int fd, void *buf, size_t count);
sszie_t  write(int fd, const void *buf, size_t count);
off_t    lseek(int fd, off_t offset, int whence);

实现描述

将源文件拷贝到目标文件中,通过读和写的操作完成

测试代码

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

int main(int args,char *argv[])
{
	int fd_Src;
	int fd_Des;
	int n_read;
	int n_write;
	int len;
	char readbuf[128];
	
	memset(readbuf,0,sizeof(readbuf)/sizseof(char)); //初始化
	if(args!=3) //判断参数
	{
		perror("input error");
	}
	if((fd_Src=open(argv[1],O_RDWR))==-1) //源文件的读
	{
		perror("open fd_Src");
		exit(-1);
	}
	len=lseek(fd_Src,0,SEEK_END);//返回源文件的大小
	lseek(fd_Src,0,SEEK_SET);   //移到头位置
	if((n_read=read(fd_Src,readbuf,len))==-1)
	{
		perror("read");
		exit(-1);
	}
	if((fd_Des=open(argv[2],O_RDWR||O_CREAT,0666))==-1)
	{
		perror("open fd_Dec");
		exit(-1);
	}
	if((n_write=write(fd_Des,readbuf,sizeof(readbuf)/sizeof(char)))==-1)
	{
		perror("write");
		exit(-1);
	}
	printf("read size=%d,read file:%s\n",n_read,readbuf);
	printf("write size=%d",n_write);
	close(fd_Src);
	close(fd_Des);
	return 0;
}

测试结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值