关于系统IO与标准IO 的区别可以参看以下链接
https://mp.csdn.net/mp_blog/creation/editor/119696769
系统IO:系统IO又称文件IO,也称低级磁盘IO,属于不带缓存的IO(unbuffered I/O)。
函数原型(API):
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);函数功能:打开文件
头文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>形参作用:
pathname :被操作文件路径名(const修饰的pathname函数调用后不改变)flags :打开文件后对文件的操作权限
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 可读可写
O_CREAT 如果文件不存在则创建
O_EXCL 如果文件存在则报错
O_TRUNC 如果文件存在,则清空
O_APPEND 以追加的形式打开文件mode :如果flags使用了O_CREAT,才用第三
个参数,没有O_CREAT则不需要 , 例如:0777
注意这里的mode创建了文件的权限与系统的umask值有关,所以并不是参数mode等于0777,创建得到的权限值应该位 mdoe & (~umask)。可以通过一下命令查看 $ umask
不同操作系统umask可能不会一样,这里我就以umask002 , mode等于0777为例 ,
假设调用函数open("hello.txt" , O_WROLNY | O_CREAT , 0777)产生的新文件“hello.txt”权限值为775(111 111 101)
返回值:
成功:返回一个新的文件描述符(非负整数)
失败:-1
函数原型(API):
函数功能:根据文件描述符把数据写入文件
头文件:
#include <unistd.h>
函数原型(API):
ssize_t write(int fd, const void *buf, size_t count);ssize_t 是这里面的宏定义,看起来很吓人,实则子老虎,等于int
形参作用:
fd: 被操作文件的描述符 (open函数后的返回值)
buf:存储写入文件数据的地址
count:写入文件数据的字节
返回值:
成功:返回成功写入文件数据的字节数
失败:-1
头文件 : #include <unistd.h>API 接口 : ssize_t read(int fd, void *buf, size_t count);
函数作用 : 读取文件内容
形参作用:
fd: 被操作文件的文件描述符
buf:存储从文件读取的数据地址
count:读取文件数据的字节
返回值:
成功:返回成功读取数据的字节数
0 : 表示文件数据已经读完
失败:-1
当打开文件时 ,会有一个叫文件指针的东西,它的作用:记录操作数据的位置
使用open函数打开文件时,文件位置指针一般默认指向开头位置
函数功能:偏移文件位置指针
头文件:
#include <sys/types.h>
#include <unistd.h>API 接口:
off_t lseek(int fd, off_t offset, int whence);
形参作用:
fd : 被操作文件的文件描述符
offset :偏移量(字节数),正数往后偏移,负数往前偏移
whence :基准点
SEEK_SET 文件开头位置SEEK_CUR 文件位置指针当前位置
SEEK_END 文件末尾位置
返回值作用:
成功:返回从文件开头至文件位置指针的偏移量
失败:-1
头文件 : #include <unistd.h>API 接口 : int close(int fd);
形参作用:
fd :被操作文件的文件描述符
返回值作用:
成功:0
失败:-1
示例代码 :
#include<stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
void main(int argc,char *argv[])
{
int fd=open("1.txt",O_RDONLY);
if(fd == -1)
{
perror("open 1.txt failed");
return ;
}
char buf[30]={0};
int fd3=read(fd,buf,30); //读取成功返回成功读取的字节数
close(fd);
printf("buf=%s\n",buf);
int fd2=open("2.txt",O_RDWR|O_CREAT | O_TRUNC, 0777);
write(fd2,buf,fd3);
close(fd2);
}
“1.txt”内容为hello world , 运行结果为hello world , “2.txt”内容为hello world
有什么不足的大佬请指出来喔