Linux底层文件访问
2015年05月18日 10:52:33 Linux ⁄ 共 1829字 暂无评论 ⁄ 被围观 2,781次

第一步:新建一个名为 myfile.in 的文件,并写入一些内容,尽量多点儿。

vi myfile.in

第二步:编写文件访问功能代码。

代码一:逐个字符的文件复制程序。

编写 copy_file.c 的文件,并实现读文件和写文件的操作,编译后执行。

Code   ViewPrint
  1. #include <unistd.h>  
  2. #include <sys/stat.h>  
  3. #include <fcntl.h>  
  4. #include <stdlib.h>  
  5.   
  6. int main() {  
  7.   char c;  
  8.   int in, out;  
  9.   
  10.   in = open("myfile.in", O_RDONLY);  
  11.   out = open("myfile.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);  
  12.   while(read(in, &c, 1) == 1) {  
  13.     write(out, &c, 1);  
  14.   }  
  15.   exit(0);  
  16. }  

 

  1. $ gcc -o copy_file copy_file.c   
  2. $ ./copy_file  

 

代码二: 块形式的文件复制程序(每次复制长度为1K的数据)。

编写 copy_file_b.c 的文件,并实现读文件和写文件的操作,编译后执行。

Code   ViewPrint
  1. #include <unistd.h>  
  2. #include <sys/stat.h>  
  3. #include <fcntl.h>  
  4. #include <stdlib.h>  
  5.   
  6. int main() {  
  7.   char block[1024];  
  8.   int in, out;  
  9.   int nread;  
  10.   
  11.   in = open("myfile.in", O_RDONLY);  
  12.   out = open("myfile.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);  
  13.   while((nread = read(in, block, sizeof(block))) > 0) {  
  14.     write(out, block, nread);  
  15.   }  
  16.   exit(0);  
  17. }  

 

  1. $ gcc -o copy_file_b copy_file_b.c   
  2. $ ./copy_file_b  

 

第三步:查看是否有 myfile.out 的文件生成,并查看其中内容是否和 myfile.in 的内容一致。

  1. $ ls -ls  
  2. $ cat myfile.out  

 

第四步:代码一和代码二运行的效率的比较:

  1. # 代码一运行效率:  
  2. TIMEFORMAT="" time ./copy_file   
  3. 0.15user 21.10system 0:21.27elapsed 99%CPU (0avgtext+0avgdata 324maxresident)k  
  4. 0inputs+480outputs (0major+117minor)pagefaults 0swaps  
  5.   
  6. # 代码二运行效率:  
  7. TIMEFOEMAT="" time ./copy_file_b   
  8. 0.00user 0.02system 0:00.03elapsed 84%CPU (0avgtext+0avgdata 324maxresident)k  
  9. 0inputs+480outputs (0major+117minor)pagefaults 0swaps  

可以看到,块复制比字符复制,效率高的多,这也同时说明,频繁的系统调用需要巨大的开支。

在这里,也可以用上层函数处理文件复制:

Code   ViewPrint
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. int main() {  
  5.   int c;  
  6.   FILE *in, *out;  
  7.   
  8.   in = fopen("myfile.in""r");  
  9.   out = fopen("myfile.out""w");  
  10.   
  11.   while((c = fgetc(in)) != EOF) {  
  12.     fputc(c, out);  
  13.   }  
  14.   
  15.   exit(0);  
  16. }  

可以测出复制速度也比较快,这是因为 stdio 库在 FILE 结构里使用了一个内部缓冲区,只有在缓冲区满时才进行底层系统调用。

给我留言

留言无头像?