注:Linux 文件实现终端cp指令 (8、9节)
文件cp的自我实现:
code:
#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 agrc,char **agrv)
{
int fdSrc;
int fdDec;
char *readBuf = NULL; //指定一个野指针
if(agrc != 3){
printf("params error !!!");
exit(-1);
}//agrc 参数 ,运行参数不能少于3,否则退出
fdSrc=open(agrv[1], O_RDWR); //打开第二参数的内容
int filesize=lseek(fdSrc,0,SEEK_END); //计算打开文件的大小
lseek(fdSrc,0,SEEK_SET);//光标回归起始位置
readBuf=(char *)malloc(sizeof(char)*filesize + 8); //给野指针传参赋予大小(内存)
// ssize_t read(int fd, void *buf, size_t count);
int n_read = read(fdSrc,readBuf,filesize); //读取打开的原文件文件
// int creat(const char *pathname, mode_t mode);
fdDec=open(agrv[2], O_RDWR | O_CREAT | O_TRUNC, 0600); // 打开/创建目标文件, O_TRUNC清除该文件的内容
int n_write=write(fdDec,readBuf,strlen(readBuf)); // 写目标文件
close(fdSrc);
close(fdDec);
return 0;
}
运行结果:
CLC@Embed_Learn:~/LinuxLearn/FILE$ ./a.out demo11.c demo11cp.c
CLC@Embed_Learn:~/LinuxLearn/FILE$ cat demo11.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()
{
char *buf;
buf=(char *)malloc(sizeof(128));
int n_read = read(0,buf,128);
int n_write = write(1,buf,128);
putchar('\n');
return 0;
}
CLC@Embed_Learn:~/LinuxLearn/FILE$ cat demo11cp.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()
{
char *buf;
buf=(char *)malloc(sizeof(128));
int n_read = read(0,buf,128);
int n_write = write(1,buf,128);
putchar('\n');
return 0;
}