openat()函数的用法示例

来源:互联网 发布:太原知达常青藤中学校 编辑:程序博客网 时间:2024/06/15 20:07

《Unix环境高级编程》的第三章和第四章出现了大量的以at结尾的函数,如openat、fstatat等,书中只是粗略的说明了下,没有实际的例子让人很难懂。

[cpp] view plain copy print?
  1. int openat(int dirfd, const char *pathname, int flags, mode_t mode);  

我初看的时候有如下几个疑问:

1、按函数原型明显是要给一个目录的文件描述符,可是打开目录用的事opendir返回的是一个DIR*的指针,哪来的int型的目录文件描述符;

2、open函数常用来打开一个文件,没见过用来打开目录的;

3、如果给一个文件描述符又会报错,这个变量到底该如何赋值?

几经周折,请教了网络上的大神后终于找到了这个函数的示例函数。

用法有两种,分别说明如下。

1、直接用open打开目录,用返回值作为openat的第一个参数的值,代码如下:

[cpp] view plain copy print?
  1. #include <stdio.h>  
  2. #include <sys/stat.h>  
  3. #include <fcntl.h>  
  4. #include <stdlib.h>  
  5. #include <unistd.h>  
  6.   
  7. void creat_at(char *dir_path, char *relative_path)  
  8. {  
  9.     int dir_fd;  
  10.     int fd;  
  11.     int flags;  
  12.     mode_t mode;  
  13.   
  14.     dir_fd = open(dir_path, O_RDONLY);  
  15.     if (dir_fd < 0)   
  16.     {  
  17.         perror("open");  
  18.         exit(EXIT_FAILURE);  
  19.     }  
  20.   
  21.     flags = O_CREAT | O_TRUNC | O_RDWR;  
  22.     mode = 0640;  
  23.     fd = openat(dir_fd, relative_path, flags, mode);  
  24.     if (fd < 0)   
  25.     {  
  26.         perror("openat");  
  27.         exit(EXIT_FAILURE);  
  28.     }  
  29.   
  30.     write(fd, "HELLO", 5);  
  31.   
  32.     close(fd);  
  33.     close(dir_fd);  
  34. }  
  35.   
  36. int main()  
  37. {  
  38.     creat_at("./open""log.txt");  
  39.     return 0;  
  40. }  

2、借用dirfd,将DIR*转换成int类型的文件描述符

函数原型如下:

[cpp] view plain copy print?
  1. int dirfd(DIR *dirp);  

完整代码如下:

[cpp] view plain copy print?
  1. #include <sys/types.h>  
  2. #include <sys/stat.h>  
  3. #include <fcntl.h>  
  4. #include <dirent.h>  
  5. #include <stdio.h>  
  6. #include <unistd.h>  
  7.   
  8. int main()  
  9. {  
  10.     DIR *dir;  
  11.     int dirfd2;  
  12.     int fd;  
  13.     int n;  
  14.   
  15.     dir = opendir("./open/chl");  
  16.     if(NULL == dir)  
  17.     {  
  18.         perror("open dir error");  
  19.         return -1;  
  20.     }  
  21.     dirfd2 = dirfd(dir);  
  22.     if(-1 == dirfd2)  
  23.     {  
  24.         perror("dirfd error");  
  25.         return -1;  
  26.     }  
  27.   
  28.     fd = openat(dirfd2,"output.log",O_CREAT|O_RDWR|O_TRUNC);  
  29.     if(-1 == fd)  
  30.     {  
  31.         perror("opeat error");  
  32.         return -1;  
  33.     }  
  34.     n = write(fd,"Hello world!\n",15);  
  35.       
  36.     close(fd);  
  37.     closedir(dir);  
  38.   
  39.     return 0;  
  40.   
  41. }  

实际上感觉和open函数差不了多少,只是一个是字符串常量,一个是已经打开的文件描述符。


0 0
原创粉丝点击