本日内容讲解了有关linux系统中的缓存的作用,在linux系统中使用man 2 fopen/fclose/fread/fwrite查询手册可以获得使用格式以及返回值。
将第一日所编写的实现copy功能的程序进行深一步的改写,将其中的read、open、write改为系统缓存命令fread、fopen、fwrite,从而利用linux系统中的buf缓存来实现copy文件内容的功能。
#include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <string.h>
7
8 int main(int argc, char *argv[])
9 {
10 int ret;
11 FILE* fd_from;
12 FILE* fd_to;
13
14 if (argc != 3)
15 {
16 printf("error\n");
17 exit(1);
18 }
19 //打开源文件
20 fd_from = fopen(argv[1], "r+");
21 if (NULL== fd_from)
22 {
23 perror("open");
exit(1);
25 }
26
27 //打开目的文件
28 fd_to = fopen(argv[2], "w+");
29 if (NULL== fd_to)
30 {
31 perror("open");
32 exit(1);
33 }
34
35 char buf[32] = {0};
36
37 while ((ret = fread(buf,1,31,fd_from)) != 0)
38 {
39 ret = fwrite(buf,1,ret, fd_to);
40 if (0 == ret)
41 {
42 perror("write");
43 break; //结束循环
5 }
46 memset(buf, 0, 32); //清空buf
47 }
48
49 fclose(fd_to);
50 fclose(fd_from);
51 return 0;
52 }