文件权限操作

xiaoxiao2025-08-22  71

朱老师核心课程笔记 文件权限的操作

一. 文件权限操作 open flag位

Ⅰ 读写权限

O_RDONLY 只读O_WRONLYO 只写O_RDWRO_RDWR 读写

Ⅱ 打开存在并有内容的文件

Q_APPEND ① 追加文件内容,在原内容的基础上接续新内容O_TRUNC ① 清空原来的文件内容,新内容替代旧内容; ② 不使用则不清空原内容

*在上文文件读写操作过程中,发现写入的文件内容覆盖了原内容 *原文件内容

root@ubuntu:/mnt/hgfs/winshare/fight# cat a.txt hello world

*写入文件后

root@ubuntu:/mnt/hgfs/winshare/fight# cat a.txt hello manld

*只剩下最后ld两位

*原因: 没有加O_APPEND

fd = open("a.txt", O_RDWR | O_APPEND);

*修正后

root@ubuntu:/mnt/hgfs/winshare/fight# cat a.txt hello manld hello man

Ⅲ 打开不存在的文件

O_CREAT ① 为了打开一个未创建的文件,创建并打开; ② 如果文件存在则删除原文件,创建新文件 ③ mode 指定权限 可读可写不可执行 0666

O_EXCL ① 如果要创建一个新文件,但是命名了已有文件名,会报错; ② 创建已有文件名时,报错; ③ 创建为创建文件名时,创建该新文件

Ⅳ 阻塞与非阻塞

O_NONBLOCK ① 阻塞与非阻塞(阻塞时函数不能立刻返回,任务完成;非阻塞函数立即返回,任务不一定完成); ② 只用于设备文件,而不用于普通文件

O_SYNC ① write阻塞等待底层完成写入才返回应用层; ② 无O_SYNC时,open函数中的代码会存在底层buf中,等待硬盘一次性存入,提升硬盘使用寿命和效率。

二. 进程

在main中用return,一般程序正常结束为return 0,异常为return -1;

正式终止进程应该是使用 exit,_Exit,_exit

#include <stdlib.h>

void exit(int status);

#include <unistd.h>

void _exit(int status);

#include <stdlib.h>

void _Exit(int status);
转载请注明原文地址: https://www.6miu.com/read-5035105.html

最新回复(0)