文件I/O

来源:互联网 发布:linux 查看字符编码 编辑:程序博客网 时间:2024/05/16 01:44

1、文件描述符

文件描述符是一个非负整数,当打开一个现有文件或创建一个新文件时,内核向进程返回一个文件描述符,当读或写一个文件时,使用open或creat返回的文件描述符识别该文件,将其作为参数传递给read或write.

文件描述符就像是指向文件的指针。

标准输入0 / STDIN_FILENO

标准输出1/ STDOUT_FILENO

2、open函数  (返回最小的未用描述符数值)

#include <fcntl.h>

int open(const char *pathname, int 0flag,...);

参数:O_RDONLY  只读打开 O_WRONLY 只写打开  O_RDWR 读、写打开 等

3、creat函数 ( 创建一个新文件)

#include <fcntl.h>

int creat(const char *pathname, mode_t mode) 返回值:若成功则返回为只写打开的文件描述符,若出错则返回-1

相当于 open(pathname,O_WRONLY | O_CREAT| O_TRUNC, mode)

4、close函数

#include <unistd.h>

int close(int filedes);  若成功则返回0,若出错则返回-1

关闭一个文件时还会释放该进程加在该文件的所有记录锁

5、lseek函数

#include <unistd.h>

off_t lseek(int filedes, off_t offset, int whence); 若成功则返回新的偏移量(有可能是负数),若失败则返回-1

若whence为SEEK_SET,则将该文件的偏移量设置为距文件开始处offset个字节,若为SEEK_CUR,则为其当前值加offset,若为SEEK_END 则为文件长度加offset

6、 read函数

#include <unistd.h>

ssize_t read(int filedes, void *buf, size_t nbytes); 返回值:若成功则返回读到的字节数,若已到文件结尾则返回0,若出错则返回-1

7、write函数

#include <unistd.h>

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

8、IO效率

①用不同缓冲区长度进行读操作的结果不同,并非缓冲区越小或者越大速度就快

②预读技术

③缓存技术


原创粉丝点击