本段代码主要实现LINUX中CP复制功能:
思路:1.进行判断传递的参数是否符合语法规范
2.找到源文件Src及需要传递的文件Dse
3.通过指针readbuf在read和write中进行传递源文件
read:在Linux中包含的头文件及格式如下(具体查询 man 2 read)
//#include <unistd.h>
//ssize_t read(int fd, void *buf, size_t count);
write:在Linux中包含的头文件及格式如下(具体查询 man 2 write)
// #include <unistd.h>
// ssize_t write(int fd, const void *buf, size_t count);
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv) //传递的argc用于判断格式是否正确
{
int fdSrc;
int fdDes;
char *readbuf = NULL;
if(argc != 3){
printf(“pararm error”);
exit(-1);
}
fdSrc = open(argv[1],O_RDWR);
int size = lseek(fdSrc,0,SEEK_END);//计算大小
readbuf = (char *)malloc(sizeof(char)*size+8);
lseek(fdSrc,0,SEEK_SET);//移动光标到源文件头防止出现读源文件时报错
int n_read = read(fdSrc,readbuf,1024);
fdDes = open(argv[2],O_RDWR|O_CREAT,0600);//0600为可读4可写2操作
int n_write = write(fdDes,readbuf,strlen(readbuf));
close(fdSrc);
close(fdDes);
return 0;
}