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
Linux 文件操作总结(1)
最新推荐文章于 2024-05-10 18:12:28 发布