Linux系统编程06-open
open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char* pathname, int flags);
打开文件
作用: 打开一个已经存在的文件
-
flags 文件操作权限: O_RDONLY, O_WRONLY, or O_RDWR , 互斥
-
返回:
- 成功: 一个新的文件描述符;
- 失败: -1, 并设置errno
-
errno: 属于Linux系统函数库,库里面一个全局变量,记录最近错误号
创建文件
int open(const char *pathname, int flags, mode_t mode);
-
pathname: 创建的文件路径
-
flags: 一个int 类型的数据,占4个字节,32位。
- flags 32个位,每一位就是一个标志位。
- 多个标记 O_RDONLY, O_WRONLY, or O_RDWR (必选);
- O_CREAT 文件不存在时创建 (可选)
-
mode: 八进制数,新文件的操作权限 如:0775,最终的权限: mode & ~umask;umask 的作用是抹去某些权限
perror
#include <stdio.h>
void perror(const char *s);
参数:s: 用户描述,比如hello,最终输出:hello:xxx(实际错误描述)
实例
打开文件
a.txt
hello
nihao
open.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd = open("a.txt",O_RDONLY);
if(fd == -1)
{
perror("open failed");
// open failed: No such file or directory
}
//close
close(fd);
return 0;
}
创建文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
int fd = open("create.txt", O_RDWR | O_CREAT, 0777);
//指定的权限是777 实际的权限是775,因为~umask的存在抹去某些权限
if (fd == -1)
perror("open failed");
close(fd);
return 0;
}
本文作者:JoeのBLOG
本文链接:https://www.cnblogs.com/anqwjoe/p/16793184.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步