1.查看linux系统I/O函数格式:man 2 函数名
nowcoder@nowcoder:~/linux$ man 2 open
2.查看标准C库I/O函数格式: man 3 函数名
nowcoder@nowcoder:~/linux/lession09$ man 3 perror
// 打开一个已经存在的文件
int open(const char *pathname, int flags);
参数:
- pathname:要打开的文件路径
- flags:对文件的操作权限设置还有其他的设置
O_RDONLY, O_WRONLY, O_RDWR 这三个设置是互斥的
返回值:返回一个新的文件描述符,如果调用失败,返回-1
- open
errno:属于Linux系统函数库,库里面的一个全局变量,记录的是最近的错误号。
#include <stdio.h>
void perror(const char *s);作用:打印errno对应的错误描述
s参数:用户描述,比如hello,最终输出的内容是 hello:xxx(实 际的错误描述)
// 创建一个新的文件
int open(const char *pathname, int flags, mode_t mode);
参数:
- pathname:要创建的文件的路径
- flags:对文件的操作权限和其他的设置
- 必选项:O_RDONLY, O_WRONLY, O_RDWR 这三个之间是互斥的
- 可选项:O_CREAT 文件不存在,创建新文件
- mode:八进制的数,表示创建出的新的文件的操作权限,比如:0775
最终的权限是:mode & ~umask
0777 -> 111111111
& 0775 -> 111111101
----------------------------
111111101
按位与:0和任何数都为0
umask的作用就是抹去某些权限。
flags参数是一个int类型的数据,占4个字节,32位。
flags 32个位,每一位就是一个标志位。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int fd = open("a.txt",O_RDONLY);
if(fd == -1){
perror("open");
}
//关闭
close(fd);
return 0;
}
nowcoder@nowcoder:~/linux$ cd lession09
nowcoder@nowcoder:~/linux/lession09$ ls
open.c
nowcoder@nowcoder:~/linux/lession09$ gcc open.c -o open
nowcoder@nowcoder:~/linux/lession09$ ls
open open.c
nowcoder@nowcoder:~/linux/lession09$ ./open
open: No such file or directory
文件中没有a.txt,报出错误信息open: No such file or directory
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
// 创建一个新的文件
int fd = open("create.txt",O_RDWR| O_CREAT, 0777);
if(fd == -1){
perror("open");
}
close(fd);
return 0;
}
nowcoder@nowcoder:~/linux/lession09$ gcc create.c -o create
nowcoder@nowcoder:~/linux/lession09$ ls
create create.c create.txt open open.c
nowcoder@nowcoder:~/linux/lession09$ ll create.txt
-rwxrwxr-x 1 nowcoder nowcoder 0 3-р с 4 16:24 create.txt*
本来没有create.txt文件,自动创建了一个,注意open的第二个参数如果有多个用 | 连接,这是因为第二个参数是32位的int类型,每一位bit代表一位可执行操作,所以用或字符才能实现所有想要的操作