• Linux系统编程06open


    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;
    }
    
  • 相关阅读:
    BZOJ1119: [POI2009]SLO
    BZOJ1486: [HNOI2009]最小圈
    BZOJ1098: [POI2007]办公楼biu
    BZOJ2242: [SDOI2011]计算器
    PAT A1023
    SpringCloud之整合Feign
    SpringCloud之整合Feign
    小程序在wxml页面格式化类似的2019-02-16T10:54:47.831000时间
    小程序在wxml页面格式化类似的2019-02-16T10:54:47.831000时间
    Javascript基础之-var,let和const深入解析(二)
  • 原文地址:https://www.cnblogs.com/anqwjoe/p/16793184.html
Copyright © 2020-2023  润新知