文件IO
文件IO的概念:
什么是文件IO,又称系统IO,系统调用
是操作系统提供的API接口函数。
POSIX接口 (了解)
注意:文件IO不提供缓冲机制
文件IO的API
open close read write
文件描述符概念:
英文:缩写fd(file descriptor)
是0-1023的数字,表示文件。
0, 1, 2 的含义 标准输入,标准输出,错误
文件IO 打开
open
int open(const char *pathname, int flags); 不创建文件
int open(const char *pathname, int flags, mode_t mode); 创建文件,不能创建设备文件
成功时返回文件描述符;出错时返回EOF
文件IO和标准的模式对应关系:
r O_RDONLY
r+ O_RDWR
w O_WRONLY | O_CREAT | O_TRUNC, 0664
w+ O_RDWR | O_CREAT | O_TRUNC, 0664
a O_WRONLY | O_CREAT | O_APPEND, 0664
a+ O_RDWR | O_CREAT | O_APPEND, 0664
umask概念:
umask 用来设定文件或目录的初始权限
文件的关闭
int close(int fd)
关闭后文件描述符不能代表文件
文件IO的读写和定位
容易出错点:
求字符串长度使用strlen,对二进制数据使用sizeof
printf 的字符最后没有’\0’
关闭打开文件函数如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[]){
int fd;
int ret;
fd = open("test.txt",O_WRONLY|O_CREAT|O_TRUNC, 0666);
if(fd<0){
printf("open file err\n");
return 0;
}
printf("sucess,fd=%d\n",fd);
ret= close(fd);
if(ret<0){
printf("close failed\n");
}
ret=close(fd);
printf("ret=%d\n",ret);
}
读写文件
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char *argv[]){
int fd;
int ret;
char buf[32] = "hello world";
char buf2[32]={0};
fd = open("test.txt",O_RDWR | O_CREAT | O_APPEND, 0666);
if(fd<0)
{
printf("open file err\n");
return 0;
}
printf("sucess,fd=%d\n",fd);
ret=write(fd,buf,strlen(buf));//写字符串用strlen不用sizeof,写二进制时用sizeof
if(ret<0)
{
perror("write");
close(fd);
return 0;
}
printf("write count=%d\n",ret);
lseek(fd,0,SEEK_SET);
//close(fd); 让文件指针归零
//fd = open("test.txt",O_RDWR | O_CREAT | O_APPEND, 0666); 这两条在此程序作用同上一条
ret = read(fd,buf2,32);
if(ret<0)
{
perror("read");
close(fd);
return 0;
}
buf2[31]=0;
printf("read buf2=%s\n",buf2);
close(fd);
return 0;
}