1 思路
Linux要想复制一份文件通常指令为:
cp src.c des.c
其中src.c为源文件,des.c为目标文件。
要想通过文件编程实现cp效果,思路如下
1 首先打开源文件 src.c
2 读src到buf
3 创建des.c
4 将buf写入到des.c
5 close两个文件
2 实现
vi demo.c
#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)
{
/* 0 1 2
cp src.c des.c 3个参数 argc
|| || ||
argv[0] argv[1] argv[2]
*/
int fdSrc;
int fdDes;
char *readBuf=NULL;
if(argc != 3){
printf("pararm error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR);
int size = lseek(fdSrc,0,SEEK_END);
lseek(fdSrc,0,SEEK_SET);
readBuf=(char *)malloc(sizeof(char)*size + 8);
int n_read = read(fdSrc, readBuf, size);
fdDes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);
int n_write = write(fdDes,readBuf,strlen(readBuf));
close(fdSrc);
close(fdDes);
return 0;
}
gcc demo.c -o mycp
./mycp demo.c ./new.c
vi new.c