Linux/Unix文件和IO

栏目: 服务器 · 发布时间: 4年前

内容简介:oflag:whence:dup:返回当前可用的最小描述符

文件和IO

1.open

#include <fcntl.h>
int open(const char *path, int oflag, ...)
int openat(int fd, const char *path, int oflag, ...mode_t mode)

// success: ret=fd   ohterwise-1

oflag:

// 值根据系统而不同
#define O_RDONLY    0x0000      /* 只读 */
#define O_WRONLY    0x0001      /* 只写 */
#define O_RDWR      0x0002      /* 读写 */
#define O_ACCMODE   0x0003      /* mask for above modes */

#define O_NONBLOCK  0x0004      /* 非阻塞 no delay */
#define O_APPEND    0x0008      /* 追加 */

#define O_SYNC          0x0080      /* 使每次write等待物理IO操作完成,包括文件属性更新synch I/O file integrity */

#define O_CREAT     0x0200      /* 文件不存在则创建 */
#define O_TRUNC     0x0400      /* 文件存在且为读或读写打开,截断为0 */
#define O_EXCL      0x0800      /* 如果设置O_CREAT且存在则报错,否则创建且是原子操作 */

2.close

#include <unistd.h>
int  close(int fd)
  1. 关闭文件会释放该进程加在该文件的所有记录锁
  2. 进程终止时,内核会自动关闭它所有打开的文件

3.lseek

#include <unistd.h>
off_t    lseek(int fd, off_t offset, int whence);
// success:off_t otherwise:-1

whence:

SEEK_SET: 据文件开始off_t
SEEK_CUR:当前值加off_t, offset可正可负
SEEK_END:文件长度加off_t,offset可正可负

4.read

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t nbytes)
// success: 文件的字节数,若是文件尾返回0, 出错:-1

5.write

#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t nbytes)
// success: 已写的字节数, 出错:-1

6.dup/dup2

#include <unistd.h>
int dup(int fd)
int dup2(int fd, int fd2)
// success: 新的文件描述符, 出错:-1

dup:返回当前可用的最小描述符

dup2:fd2指定新的描述符,若fd2已经打开将其关闭,若fd和fd2相等,则不关闭

7.sync/fsync/fdatasync

#include <unistd.h>

int sync(void) // 所有
int fsync(int fd) // 指定的fd   数据+文件属性
int fdatasync(int fd) // 指定的fd  数据
// success: 0, 出错:-1

8.fcntl

#include <fcntl.h>

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

// success: 依赖于cmd, 出错:-1

cmd:

F_DUPFD|F_DUPFD_CLOEXEC:复制文件描述符
F_GETFD|F_SETFD:获取/设置文件描述符标志
F_GETFL|F_SETFL:获取/设置文件状态标志
F_GETOWN|F_SETOWN:获取/设置异步io所有权
F_GETLK|FSETLK:获取/设置记录锁

9.ioctl

#include <unistd.h> // #include <sys/ioctl.h> //linux

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

// success: 其他值, 出错:-1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Writing Windows VxDs and Device Drivers, Second Edition

Writing Windows VxDs and Device Drivers, Second Edition

Karen Hazzah / CMP / 1996-01-12 / USD 54.95

Software developer and author Karen Hazzah expands her original treatise on device drivers in the second edition of "Writing Windows VxDs and Device Drivers." The book and companion disk include the a......一起来看看 《Writing Windows VxDs and Device Drivers, Second Edition》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

随机密码生成器
随机密码生成器

多种字符组合密码