星巡研究院

open()

fcntl.h
int open(const char *pathname, int flags, ... /* mode_t mode */);

打开或创建文件并返回文件描述符,标志位决定读写方式与创建行为。

# open · 打开或创建文件 ## 头文件 `fcntl.h`(mode 定义在 `sys/stat.h`) ## 函数原型 `int open(const char *pathname, int flags, ... /* mode_t mode */);` ## 说明 open 把路径映射成一个文件描述符,后续 read / write / lseek / close 都基于它。成功返回 fd,失败返回 -1。 常用 flags: - O_RDONLY / O_WRONLY / O_RDWR:三选一的访问方式 - O_CREAT:文件不存在则创建,此时需要第三个参数 mode(如 0644) - O_TRUNC:打开时把文件截断为 0 - O_APPEND:每次写都追加到文件末尾 - O_NONBLOCK:非阻塞模式 ## 最小示例 ```c #include <fcntl.h> #include <unistd.h> int main(void) { int fd = open("demo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { return 1; } write(fd, "hello\n", 6); close(fd); return 0; } ``` ## 常见坑 - 用了 O_CREAT 却忘了传 mode,创建出的文件权限不可预期 - 文件权限位看起来对却打不开——还要看所在目录的执行位与文件所有者 - 多个进程同时写同一文件却没加 O_APPEND,内容互相覆盖 - 忘记 close,fd 泄漏 ## 相关函数 read、write、close、lseek、fstat、creat