现在的位置: 首页 > 综合 > 正文

【学习笔记】Linux平台的文件I/O操作

2013年06月15日 ⁄ 综合 ⁄ 共 1335字 ⁄ 字号 评论关闭

以下函数为不带缓存的I/O(unbuffered I/O)函数

对于内核而言,所有打开的文件都由一个非负整数描述(称为文件描述符)。

下面介绍下文件I/O函数:

(1)open

此函数为打开或创建一个文件。成功则返回文件描述符;失败则返回-1。

格式:

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int open(const char *name, int oflag[|optional parameter][,mode]);

(2)creat

此函数为创建一个新文件。成功则返回文件描述符;失败则返回-1。

格式:

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int creat(const char *name, mode_t mode);

(3)close

此函数为关闭一个已经打来的文件。

格式:

#include <unistd.h>

int close(int file);

成功返回0,否则返回-1。

(4)lseek

此函数为制定一个当前文件位移量。这个位移量是一个非负整数,用来说明从文件开始处计算的字节数。

格式:

#include <unistd.h>

#include <sys/types.h>

off_t lseek(int file, off_t offset, int whence);

成功返回文件位移;出错返回-1。

(5)reed

此函数为从文件中读入数据。

格式:

#include <unistd.h>

size_t read(int file, void *buf, size_t bytes);

返回读到的字节书,若已读到尾部则返回0,若出错返回-1。

(6)write

此函数为向文件中写入数据。

格式:

#include <unistd.h>

size_t write(int file, void *buff, size_t bytes);

返回写入文件的字节总数,大小一定小于缓冲区容量。出错返回-1。

(7)dup

此函数可以用来复制一个现存的文件描述符。

格式:

#include <unistd.h>

int dup(int oldfile);

int duo2(int oldfile, int newfile);//可以指定新文件的描述符

成功返回次新文件的文件描述符;失败返回-1 。

(8)fcntl

用途1:复制描述符(cmd=F_DUPED)

用途2:获取/设置文件爱你描述符标志

用途3:获取文件状态标志

用途4:获取/设置记录锁

用途5:获取/设置异步I/O

格式:

#include <unistd.h>

#include <fcntl.h>

int fcntl(int fd, int cmd);


int fcntl(int fd, int cmd, long arg);


int fcntl(

int fd, int cmd, struct flock *lock);

(9)ioctl

此函数是input/output control 的缩写,即输入输出控制。它可以通过一个文件描述符来控制字符设备。

格式:

#include <sys/ioctl.h>

int ioctl(int file, int request, char *argp|struct termios st);

成功返回0,出错返回-1 。

抱歉!评论已关闭.