多数Unix I/O常用的5个系统调用有functions:open,read,write,lseek and close,它们一般被称为无缓冲的I/O
无缓冲意味着每一次read, write文件都直接调用了内核的系统调用
open函数的三个参数:
(1)path是已经存在的文件的路径;
(2)oflags参数:若值为 O_RDONLY ,就以只读方式打开文件;
若值为 O_WDONLY,就以只写方式打开文件;
若值为 O_RDWR,就以读写方式打开文件;
(3)参数mode:文件的权限,对于一个已经存在的文件,参数mode是没有用的,通常将其省略,因此这种情况下open调用只需两个参数。
这篇博客把open read write 和close 的用法写得很详细
https://blog.csdn.net/MOON5555/article/details/78411514
一个write()写入文件的小例子
(我第一次写的时候报了错,因为我把O_WRONLY写成0_WRONLY,前面是大写字母O而不是数字0)
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main(){
int fd=open("./file.txt",O_WRONLY|O_CREAT);
printf("fd=%d\n",fd);
write(fd,"hellohi",7);
close(fd);
}
一个read()读出文件的小例子
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main()
{
int fd=open("file.txt",O_RDONLY);
printf("fd=%d\n",fd);
char buff[128];
read(fd,buff,127);
printf("read:%s\n",buff);
close(fd);
}
文件描述符:0 标准输入流
1 标准输出流
2 标准错误流
#include <unistd.h>
#include <stdio.h>
#define BUFSIZ 4096
int main()
{
char buf[BUFSIZ];
int numread;
while((numread = read(0, buf, sizeof(buf))) > 0)
write(1, buf, numread);
exit(0);
}
关于lseek,这篇博客写得很详细
https://www.jianshu.com/p/6b4adc33d9a9
其他可供参考的博客
https://blog.csdn.net/u011068702/article/details/54176227
https://blog.csdn.net/songyulong8888/article/details/78632289