想通过c语言简单实现cp 命令,基础原理是;
1.判断输入参数源文件和目标是否为空
2.分别使用open()系统调用打开源文件,目标文件不存在则创建目标文件
3.用read()调用将源文件内容读到缓存buf中,再调用write()函数把buf内容写到目标文件里。
注意:在验证中出现read()返回值一直是1,而不是具体读到的字节数,后来查阅资料发现是优先级问题导致:
https://www.cnblogs.com/iamrly/p/3841795.html
部分程序如下:
while(count=read(fd_s,buf,512)>0)
printf("count=%d\n",count);
write(fd_d,buf,count);
打印出来的count始终1,
原因:运算符优先级的问题。
改为:while((count=read(fd_s,buf,512))>0) 运行正确。
如下是简单CP 命令实现代码:
#include<stdio.h>
#include<string.h>
#include <errno.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFSIZE 1024 //定义缓存大小为1024字节
int main(int argc,char*argv[])
{
int sourfd,dstfd,numRead,numWrite;
int totalByte=0;
char buf[BUFSIZE];
if(argv[1]==NULL||argv[2]==NULL) //判断输入源文件目标文件参数是否为空
{
printf("Usage:%s sourfile dstfile\n",argv[0]);
exit(0);
}
if((sourfd=open(argv[1],O_RDONLY))==-1) //打开源文件
{
perror("open");
}
printf("open %s succeed\n",argv[1]);
if((dstfd=open(argv[2],O_CREAT|O_WRONLY))==-1) //打开目标文件,不存在则创建目标文件
{
perror("open");
}
printf("open %s succeed\n",argv[2]);
//system("ls -l");
while((numRead=read(sourfd,buf,BUFSIZE))>0) //从源文件中读取数据到buf
{
printf("read:%d\n",numRead);
if(((numWrite=write(dstfd,buf,numRead)))!=numRead) //从缓存buf中读数据到目标文件
{
perror("write");
}
printf("write total %d byte to %s\n",totalByte+=numWrite,argv[2]);
}
//关闭目标文件源文件
close(sourfd);
printf("close sourfd\n");
close(dstfd);
printf("close dstfd\n");
return 0;
}
运行结果如下:
zdg@localhost Thread]$ ./my_cp fork.c 2.c
open fork.c succeed
open 2.c succeed
read:706
write total 706 byte to 2.c
close sourfd
close dstfd
[zdg@localhost Thread]$