文件打开及创建 您所在的位置:网站首页 open文件权限 文件打开及创建

文件打开及创建

2023-03-20 04:38| 来源: 网络整理| 查看: 265

打开文件,Linux给我们提供了一个open函数

需要包含三个头文件

#include #include #include

API说明

int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode);

参数说明:

pathname:要打开的文件名(含路径,缺省为当前路径)

flags:权限。具体有

O_RDONLYOD 只读打开; O_WRONLY:只写打开;O_RDWR:可读可写打开

代码如下

file存在的情况

#include #include #include #include int main() { int fd; fd = open("./file1", O_RDWR); printf("fd=%d\n",fd); // fd=3 return 0; }

file1不存在

printf("fd=%d\n",fd); // fd=-1

也就是说失败会返回 -1;

现在可以利用这个实现,没有文件则创建一个

#include #include #include #include int main() { int fd; fd = open("./file1", O_RDWR); if(fd == -1){ printf("open file1 failed\n"); fd = open("./file1", O_RDWR | O_CREAT, 0600); // 0600 是权限 if(fd > 0){ printf("create file1 sucess\n"); } } printf("fd = %d\n",fd); return 0; }

结果为:

当我们附带了权限后,打开的文件就只能按照这种权限来操作。

以上这三个常数中应当只指定一 个。下列常数是可选择的:

O_CREAT 若文件不存在则创建它。

使用此选项时,需要同时说明第三个参数mode,用其说明该新文件的存取许可权限。

O_EXCL 如果同时指定了OCREAT,而文件已经存在,则出错。

O_APPEND 每次写时都加到文件的尾端。

O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0。

Mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限

分析文件:ls -l

rwx前面的 - 代表是一个普通文件

rwx:

r:是可读权限

w: 是可写权限

x: 可执行权限

可以看到file1,在创建的时候,给的的权限是0600,现在解释0600

通常情况下

r:是可读权限 4

w: 是可写权限 2

x: 可执行权限 1

6 = 4 + 2

所有在上面的会看到创建出来的file1是rw (可读可写)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有