系统编程 -文件io访问基本操作
导:所有的 I/O 操作都是通过读文件或者写文件来完成的!(文件:在这里,把所有的外围设备,包括键盘和显示器,都看成是文件系统中的文件)
“Linux 中一切皆文件":传统的操作系统来说,普通的 I/O 操作一般会被内核缓存,这种 I/O 被称作缓存I/O。现在所提到的文件访问机制不经过操作系统内核的缓存,数据直接在磁盘和应用程序地址空间进行传输,故该文件访问的机制称作为直接 I/O 。
直接 I/O 是一种非常高效的手段。
linux系统系统操作的开关读写建的系统库包含:(可以使用man 2 open/creat/write等查看需要包含的文件库)
#include <unistd.h> //close read
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
1.开 open函数 open 的两个原型
int open(const char *path, int oflags,mode_t mode);
//第一个参数 path 表示:路径名或者文件名。路径名为绝对路径名,例如开发板中的 led驱动的设备几点/dev/leds。
//第二个参数 oflags 表示:打开文件所采取的动作。
//第三个参数 mode 表示:设置创建文件的权限
int open(const char *path, int oflags);
//返回一个文件句柄,文件句柄是文件的唯一识别符 ID
//两个参数的 open 函数主要用于创建文件的路径和文件采取的动作
================
2 关close
任何一个文件在操作完成之后都需要关闭,这个时候需要调用 close 函数!
int close(int fd);
//参数 fd,使用 open 函数打开文件之后返回的句柄。
//返回值,一般很少使用 close 的返回值。
3.读 read
对文件进行写操作,read 函数使用的比较多( 可先学习如何写 在作读操作 更容易理解 )
函数原型为: ssize_t read(int fd,void *buf,size_t len)
//参数 fd,使用 open 函数打开文件之后返回的句柄。
//参数*buf,读出的数据保存的位置。
//参数 len,每次最多读 len 个字节。
//返回值为 ssize 类型,出错会返回-1,其它数值表示实际写入的字节数,返回值大于 0 小于 len 的数值都是正常的。
#include <unistd.h> //close read
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
main()
{
int fd;
ssize_t ret,len_w,len_r=MAX_LEN;
char *testwrite = "/bin/testwrite";
char readbuffer[]="hello_read_exampler!";
char writebuffer[MAX_LEN];
if((fd=open(testwrite,O_RDWR | O_CREAT ,0777))<0)
{
printf("open %s err!\r\n",testwrite); //1
}else printf("open %s ok!\r\n",testwrite);
if((len_w=write(fd,readbuffer,strlen(readbuffer)))<0)
{
printf("write err \r\n");
}else printf("write ok! \r\n"); //2
close(fd);//--------关闭后重新读---------------
if((fd=open(testwrite,O_RDWR | O_CREAT,0777))<0)
{
printf("open %s err!\r\n",testwrite);
}else printf("open %s ok!\r\n",testwrite); //3
if((ret=read(fd,readbuffer,len_r))<0)
{
printf("read err \r\n");
}else printf("read OK ! \r\n"); //4
close(fd);//--------关闭---------------------
}
4 写 write
对文件进行写操作,write 函数使用的比较多
`函数原型为 ssize_t write(int fd,const void *buf,size_t count)
//参数 fd,使用 open 函数打开文件之后返回的句柄。
//参数*buf,需要写入的数据。
//参数 count,将参数*buf 中最多 count 个字节写入文件中。
//返回值为 ssize 类型,出错会返回-1,其它数值表示实际写入的字节数。
编写简单的 write.c 文件测试 write 函数================
5.建立 creat
关于 creat 函数,首先这个单词并不是表示创建的意思,创建的英文单词是“create”,这是早期的一个小的拼写错误,却一直沿用下来。
在介绍 open 函数的时候,可以看到 open 函数有两种形式,一个是两个参数一个是三个参数,早期的时候 open 只有三个参数的形式,三个参数的形式会导致 open 函数无法打开一个未创建的文件,也就是无法建立文件,所以就有了这个 creat 函数。
现在 creat 函数可以完全用 open 替代,考虑到在阅读代码的时候可能会碰到,所以简单介绍一下。
creat 函数原型如下。int creat(const char * pathname, mode_t mode);//creat 只有两个参数,参数含义和 open 类似。
大家看到这个函数的时候知道它是创建文件的就行,在写代码的时候完全可以用 open 代替。
编写简单的 creat.c 文件测试 creat 函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)