linux系统编程CP小测试

CP小测试

目的:把源文件copy到目标文件中。
思路:
1.打开源文件(src.c)
2.把源文件内容读取到缓存区中
3.打开目标文件(des.c)(没有就创建)
4.将缓存区里的内容写到目标文件里
5.最后关闭两个文件
实现代码:

  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <fcntl.h>
  5 #include <stdlib.h>
  6 #include <unistd.h>
  7 
  8 int main(int argc, char **argv)
  9 {
 10         int fdSrc;
 11         int fdDest;
 12 
 13         if(argc != 3)
 14         {
 15                 printf("parameter error\n");
 16                 exit(-1);
 17         }
 18 
 19         fdSrc = open(argv[1], O_RDWR);//打开源文件
 20         if(fdSrc == -1)
 21         {
 22                 printf("open error\n");
 23                 exit(-1);
 24         }
 25 
 26         int size = lseek(fdSrc, 0, SEEK_END);//移动光标计算文件大小
 27 
 28         lseek(fdSrc, 0, SEEK_SET);//让源文件光标回到开头
 29 
 30         char *readBuf = (char *)malloc(sizeof(char)*size);//开辟这么大的缓存区
 31 
 32         int n_read = read(fdSrc, readBuf, size);//从源文件读取文件到缓存区
 33         if(n_read == -1)
 34         {
 35                 printf("read source file failed\n");
 36                 exit(-1);
 37         }
 38 
 39         printf("read %d byte\n", n_read);
 40 
 41         lseek(fdSrc, 0, SEEK_SET);//让缓存区的光标回到开头
 42 
 43         fdDest = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0600);//打开或者创建或者干掉目标文件里的内容
 44         if(fdDest == -1)
 45         {
 46                 printf("open object file failed\n");
 47                 exit(-1);
 48         }
 49 
 50         int n_write = write(fdDest, readBuf, n_read);//从缓存区写数据到目标文件
 51         if(n_write == -1)
 52         {
 53                 printf("write byte error\n");
 54         }
 55         printf("write %d byte\n", n_write);
 56
 57 		close(fdSrc);
 58			close(fdDest);
 59         return 0;
 60 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值