openat函数的用法示例
来源:互联网 发布:网络攻防实验报告 编辑:程序博客网 时间:2024/05/18 03:14
《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类型的文件描述符
函数原型如下:
int dirfd(DIR *dirp);
完整代码如下:
#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函数差不了多少,只是一个是字符串常量,一个是已经打开的文件描述符。
2 0
- openat函数的用法示例
- openat()函数的用法示例
- openat函数用法示例
- openat用法
- strtok函数的用法示例
- linux openat与open函数区别
- ORACLE 的trunc函数用法示例
- biosdisk函数的用法及示例
- OpenAT实现FTP Client 的 DOTA
- 排名函数用法示例
- scanf()函数用法示例
- canny函数用法示例
- sobel函数用法示例
- Laplacian函数用法示例
- Scharr函数用法示例
- HoughLines函数用法示例
- HoughLinesP函数用法示例
- HoughCircles函数用法示例
- cocos2dx3.0戳青蛙游戏(打地鼠)
- 深入Java集合学习系列:HashSet的实现原理
- hdu 2095 find your present (2)
- Scala 深入浅出实战经典 第12讲:Scala中的继承:超类的构造、重写字段、重写方法代码实战
- iOS Cell异步图片加载优化,缓存机制详解。
- openat函数的用法示例
- 创建删除节点
- Scala 深入浅出实战经典 第13讲:抽象类、抽象字段、抽象方法
- Scala 深入浅出实战经典 第14讲:Scala中作为接口的trait、在对象中混入trait代码实战
- 欢迎使用CSDN-markdown编辑器
- IAccount
- Asp.mvc ~ 路由
- Max Sequence
- POJ2777 - Count Color (线段树 区间更新)