1.引入:
在ubuntu终端 我们使用这个指令cp a.c b.c
这个指令的意思是将a.c文件中的内容,创建b.c,把a.c的内容复制到b.c中。
2.思路:
a.打开源文件.c
b.读源文件到buf
c.打开、创建目标文件.c
d.将buf写入到目标文件.c;
e.close 关闭两个文件。(cp操作完成之后,关闭动态文件);
3.实现代码如下:
#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)
{
char *readBuf=NULL;
int fdsrc;//source file`s src
int fdDes;//destintional file
if(argc != 3){
printf("param error\n");
exit(-1);
}
fdsrc = open(argv[1],O_RDWR);
int size = lseek(fdsrc,0,SEEK_END);
lseek(fdsrc,0,SEEK_SET);
// fd = open("./file",O_RDWR|O_CREAT,0600);
readBuf = (char *)malloc(sizeof(char)*size + 8);
int n_read=read(fdsrc,readBuf,size);
fdDes = open(argv[2],O_RDWR|O_CREAT,0600);
int n_write = write(fdDes,readBuf,strlen(readBuf));
close(fdsrc);
close(fdDes);
return 0;
}