Linux系统学习——实现cp指令拷贝

系统管理员 2023-03-06 05:58 22阅读 0赞

Linux下实现cp指令的功能:

头文件可以通过使用 man 手册查询

  1. #include<stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include<stdlib.h>
  7. #include<string.h>
  8. int main(int argc, char **argv)
  9. {
  10. int fdsr; // 创建两个文件描述符
  11. int fdcr;
  12. char *buf = NULL; // 用于存放文件数据
  13. if(argc != 3) // cp a b 这样参数有三个才为正确,其他都是操作有误
  14. {
  15. printf("操作参数有问题\n");
  16. perror("why :");
  17. exit(-1);
  18. }
  19. fdsr = open(argv[1],O_RDWR); //打开第一个参数的文件,设置为可读可写
  20. if(fdsr == -1) // 检验文件是否打开失败,失败返回 -1
  21. {
  22. printf("open failed\n");
  23. }
  24. int size = lseek(fdsr,0,SEEK_END); //光标从末尾开始,返回值为文件的数据长度
  25. lseek(fdsr,0,SEEK_SET); //重置光标位置到开头位置,也就是读完整个数据后开始的位置
  26. buf = (char *)malloc(sizeof(char)*size + 8); // 开辟存放文件数据的空间大小
  27. int n_read = read(fdsr,buf,size); // 读入数据
  28. fdcr = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600); // 打开第二个参数文件
  29. int n_write = write(fdcr,buf,strlen(buf)); // 把fdsrc读入buf的数据,输送到fdcr这个文件
  30. //从而实现文件拷贝cp指令
  31. close(fdsr); //操作完一定要关闭文件,防止损坏文件
  32. close(fdcr);
  33. return 0;
  34. }

发表评论

表情:
评论列表 (有 0 条评论,22人围观)

还没有评论,来说两句吧...

相关阅读