openat函式的用法示例

2021-07-04 17:15:28 字數 1338 閱讀 7828

《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 #include #include #include #include void creat_at(char *dir_path, char *relative_path)

flags = o_creat | o_trunc | o_rdwr;

mode = 0640;

fd = openat(dir_fd, relative_path, flags, mode);

if (fd < 0)

write(fd, "hello", 5);

close(fd);

close(dir_fd);

}int main()

2、借用dirfd,將dir*轉換成int型別的檔案描述符

函式原型如下:

int dirfd(dir *dirp);

完整**如下:

#include #include #include #include #include #include int main()

dirfd2 = dirfd(dir);

if(-1 == dirfd2)

fd = openat(dirfd2,"output.log",o_creat|o_rdwr|o_trunc);

if(-1 == fd)

n = write(fd,"hello world!\n",15);

close(fd);

closedir(dir);

return 0;

}

實際上感覺和open函式差不了多少,只是乙個是字串常量,乙個是已經開啟的檔案描述符。

truncate 函式用法示例

oracle trunc 函式的用法 日期 select trunc sysdate from dual 2015 03 23 今天的日期為2015 03 23 select trunc sysdate,mm from dual 2015 03 01 返回當月第一天.select trunc sys...

ORACLE 的trunc函式用法示例

1.trunc for dates trunc函式為指定元素而截去的日期值。其具體的語法格式如下 trunc date fmt 其中 date 乙個日期值 fmt 日期格式,該日期將由指定的元素格式所截去。忽略它則由最近的日期截去 下面是該函式的使用情況 trunc to date 24 nov 1...

php json相關函式用法示例

函式列表 函式描述 json encode 程式設計客棧 對變數進行json編碼 json decode 對json格式的字串進行解碼,轉換為php變數 json last error 返回最後發生的錯誤 for example 1 json encode arr array a a b b c c...