Linux 文件操作总结(1)

Linux 文件操作总结(1)

 

准备测试文件

(2) 按字节大小分割

split -b 10m access.log new_file_prefix

 

(1) 按行数分割

split -l 300 access.log new_file_prefix

 

不带缓存的I/O 函数

1)o p e n、r e a d、w r i t e、lseek 、c l o s e

单个进程和文件描述符的关系

多个进程和文件描述符的关系

 

测试read、write函数的效率

查看os系统页的大小

[oracle@skate-test~]$ getconf PAGESIZE

4096

 

经过测试读、写文件的时候,设置缓冲区的大小为4096时,文件的读写速度是最快的。

 

测试代码:

#include"apue.h"

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

 

#defineBUFFSIZE        40960

 

Int main(void)

{

        int             n;

        char   buf[BUFFSIZE];

        int fd =open("./testaa",O_RDONLY);

        if(-1 == fd){

                printf("file openerror\n");

                exit(-1);

        }

 

        int fd2 =open("./sync1",O_RDWR |O_CREAT | O_APPEND);

        if(-1 == fd2){

                printf("file openerror\n");

                exit(-1);

        }

        while ((n = read(fd, buf, BUFFSIZE))> 0)

        {

                if (write(fd2, buf, n) != n)

                        err_sys("writeerror");

        }

        if (n < 0)

                err_sys("read error");

        close(fd);

        exit(0);

}

可以修改参数BUFFSIZE进行测试。time命令用于统计给定命令所花费的总时间。使用者可以自行修改测试代码进行验证。

例如结果如下:

[root@localhost fileio] time ./mycat

real  0m0.042s

user 0m0.002s

sys   0m0.041s

 

文件操作相关的同步问题

Case1 多进程在文件末尾追加数据

解决方法:打开文件时设置O _ A P P E N D标志

 

例如:

程序1:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define  BUFFSIZE 1024

int main(void)

{

    int fd = open("./sync1",O_RDWR|O_CREAT | O_APPEND);

     if(-1 == fd){

         printf("file open error\n");

         exit(-1);

     }

     while(1){

         if(write(fd, "aaa", 3) != 3){

              close(fd);

              exit(-1);

         }

              sleep(1);  //让出CPU

     }

     close(fd);

     exit(0);

}

程序2:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>


 #define  BUFFSIZE 1024



int main(void)

{

     int fd = open("./sync1",O_RDWR|O_CREAT | O_APPEND);

     if(-1 == fd){

         printf("file open error\n");

         exit(-1);

     }

     while(1){

         if(write(fd, "4444", 4) !=4){

              close(fd);

              exit(-1);

         }

         sleep(1); //让出CPU

     }

     close(fd);

     exit(0);

}

 

输出效果:

aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa4444aaa


 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值