文件I/O

来源:互联网 发布:淘宝商品质量问题退钱 编辑:程序博客网 时间:2024/06/03 18:38

概述:

本次讨论的文件IO是无缓冲的IO

文件的操作对应的函数有open write lseek read 

文件描述符:

文件描述符随着文件被创建或打开而产生,又由内核返回给进程,可以作为参数传递给读和写函数

文件描述符0对应着标准输入 通常替换 STDIN_FILENO

文件描述符1对应着标准输出 通常替换 STDOUT_FILENO

文件描述符3对应着标准错误 通常替换 STDERR_FILENO

函数:

open:

#include <fcntl.h>

int open(const char *path,int aflag,....)

int openat(int fd,const char *path,int aflag,....)

成功返回文件描述符,失败返回-1

这两个函数都是可变参数函数

creat:

#include <fcntl.h>

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

次函数等效于int open (path,O_WRONLY | O_CREAT | O_TRUNC,mode);

成功返回文件描述符,失败返回-1

close:

#include <unistd.h>

int close (int fd);

功返回0,失败返回-1


lseek:

每次打开一个文件都有一个与其相关的文件偏移量,表示从文件的开始处计算的字节数,默认偏移量为0

#include <unistd.h>

off_t lseek(int fd, off_offset,int whence);

若成功返回新的文件偏移量,失败返回-1

通常在比较lseek的返回值是要测试其是否为-1

read:

#include <unistd.h>

ssize_t read (int fd,void *buf,size_t nbytes)

返回值:成功是读到的字节数,若已到文件末尾则返回0,失败是,-1


write:

#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t nbytes);

返回值:成功已写的字节数,失败是,-1

fcntl


#include <fcntl.h>

int fcntl(int fd, int cmd,....)

根据cmd的不同取值,fcntl函数有不同的功能


ioctl函数

#include <unistd.h>

int ioctl(int fd,int request,.....)