首页 > 系统相关 >Linux系统编程06-open

Linux系统编程06-open

时间:2022-10-14 22:13:23浏览次数:46  
标签:文件 权限 06 int fd Linux include 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;
}

标签:文件,权限,06,int,fd,Linux,include,open
From: https://www.cnblogs.com/anqwjoe/p/16793184.html

相关文章

  • Linux系统编程05-GDB调试
    首先需要加入调试选项-g,在可执行文件中加入源代码信息,打开所有警告-Wallgcc-g-Wallprogram.c-oprogram启动:gdb可执行程序退出:quit设置参数:set......
  • Linux系统编程04-Makefile
    文件命名:makefile或Makefile规则:一个Makefile文件中可以有一个或多个规则目标...:依赖...​ 命令(shell命令)​ ...目标:最终生成的文件依赖:......
  • Linux系统编程07-read和write
    read和write函数#include<unistd.h>ssize_tread(intfd,void*buf,size_tcount);参数:fd:文件描述符,open得到的,用来操作某个文件buf:要读取数据......
  • 《Unix/Linux系统编程》第四章学习笔记 20201209戴骏
    第四章并发编程知识点归纳1、并行计算导论在早期,大多数计算机只有一个处理组件,称为处理器或中央处理器(CPU)。受这种硬件条件的限制,计算机程序通常是为串行计算编写的。......
  • 刷题 LeetCode 203 707 206
    代码随想录LeetCode203. 移除链表元素carl链表#dummyNode思路借助dummyNode简化判断条件细节dummyNode方法保持操作一致性LeetCode707. 设计链表carl......
  • Linux常用命令
    cd:切换目录用法:cd绝对路径切换路径cd相对路径切换路径cd~或者cd回到自己的家目录(root目录)cd-回到上一次所在目录cd..回到当前目录的上一......
  • 代码随想录算法训练营第三天 | 203.移除链表元素 707.设计链表 206.反转链表
    链表的数据结构基础链表结构链表是一种通过指针串联在一起的线性结构。每一个节点由两钟部分构成,一部分是数据域,一部分是指针域,指针域存放的指针指向另一个节点。链表......
  • Linux自定义别名alias重启失效问题
    linux上的别名功能非常方便:aliaslk='ls-lh'aliasll='ls-il'aliasla='ls-al'电脑重启后失效。解决方式是:vi~/.bashrcaliaslk='ls-lh'aliasll='ls-il'......
  • C++ openCV 相关
    1.opencv的Mat矩阵Mat是opencv在C++中的一个图像容器类,可以使用Mat进行图像矩阵的定义Mat矩阵的定义#include<iostream>#include<opencv2/opencv.hpp>//定义图像......
  • openssl 生成密钥
    1、下载OpenSSL工具地址:http://slproweb.com/products/Win32OpenSSL.html2、配置OpenSSL的环境变量3、生成rsa密钥命令opensslgenrsa-outrsa_private_key.pem2......