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 }