《Unix环境高级编程》的第三章和第四章出现了大量的以at结尾的函数,如openat、fstatat等,书中只是粗略的说明了下,没有实际的例子让人很难懂。
- int openat(int dirfd, const char *pathname, int flags, mode_t mode);
我初看的时候有如下几个疑问:
1、按函数原型明显是要给一个目录的文件描述符,可是打开目录用的事opendir返回的是一个DIR*的指针,哪来的int型的目录文件描述符;
2、open函数常用来打开一个文件,没见过用来打开目录的;
3、如果给一个文件描述符又会报错,这个变量到底该如何赋值?
几经周折,请教了网络上的大神后终于找到了这个函数的示例函数。
用法有两种,分别说明如下。
1、直接用open打开目录,用返回值作为openat的第一个参数的值,代码如下:
- #include <stdio.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <unistd.h>
-
- void creat_at(char *dir_path, char *relative_path)
- {
- int dir_fd;
- int fd;
- int flags;
- mode_t mode;
-
- dir_fd = open(dir_path, O_RDONLY);
- if (dir_fd < 0)
- {
- perror("open");
- exit(EXIT_FAILURE);
- }
-
- flags = O_CREAT | O_TRUNC | O_RDWR;
- mode = 0640;
- fd = openat(dir_fd, relative_path, flags, mode);
- if (fd < 0)
- {
- perror("openat");
- exit(EXIT_FAILURE);
- }
-
- write(fd, "HELLO", 5);
-
- close(fd);
- close(dir_fd);
- }
-
- int main()
- {
- creat_at("./open", "log.txt");
- return 0;
- }
2、借用dirfd,将DIR*转换成int类型的文件描述符
函数原型如下:
完整代码如下:
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <dirent.h>
- #include <stdio.h>
- #include <unistd.h>
-
- int main()
- {
- DIR *dir;
- int dirfd2;
- int fd;
- int n;
-
- dir = opendir("./open/chl");
- if(NULL == dir)
- {
- perror("open dir error");
- return -1;
- }
- dirfd2 = dirfd(dir);
- if(-1 == dirfd2)
- {
- perror("dirfd error");
- return -1;
- }
-
- fd = openat(dirfd2,"output.log",O_CREAT|O_RDWR|O_TRUNC);
- if(-1 == fd)
- {
- perror("opeat error");
- return -1;
- }
- n = write(fd,"Hello world!\n",15);
-
- close(fd);
- closedir(dir);
-
- return 0;
-
- }
实际上感觉和open函数差不了多少,只是一个是字符串常量,一个是已经打开的文件描述符。
|