日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux opendir readdir closedir 的使用

發(fā)布時間:2025/4/5 linux 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux opendir readdir closedir 的使用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2012-06-04 10:27

linux opendir readdir closedir 的使用

在Linux下opendir()、readdir()和closedir()這三個函數(shù)主要用來遍歷目錄。在使用這三個函數(shù)前必須先包括以下兩個頭文件:#include <sys/types.h>#include <dirent.h>

opendir函數(shù)的原型為:
DIR *opendir(const char *name);它返回一個DIR*類型,這就是一個句柄啦,你不用管它的內(nèi)部結(jié)構(gòu)是什么樣的,只要知道這個句柄就是等一下要傳給readdir()函數(shù)的參數(shù)就行了。

readdir函數(shù)的原型為:struct dirent *readdir(DIR *dir);看它的參數(shù)就知道該參數(shù)是opendir函數(shù)返回的句柄,而該函數(shù)的返回值是struct dirent* 類型,這里我們必須了解一下這個結(jié)構(gòu)體:struct dirent {?????????????? ino_t????????? d_ino;?????? /* inode number */
?????????????? off_t????????? d_off;?????? /* offset to the next dirent */
?????????????? unsigned short d_reclen;??? /* length of this record */
?????????????? unsigned char? d_type;????? /* type of file */
?????????????? char?????????? d_name[256]; /* filename */
};這個結(jié)構(gòu)體的d_name存放的就是文件的名字,這里的文件包括普通文件,目錄文件等等,在linux的思想中,所有的東西都是文件。
closedir函數(shù)的原型為:int closedir(DIR *dir);這個函數(shù)就不用多說了,一般有開(open),就有關(guān)(close),這樣的結(jié)構(gòu)經(jīng)??沙隹吹?#xff0c;如fopen,fclose等等。

三個函數(shù)介紹完了,直接來一個例子吧:
**********************************************SearchDir.c****************************************************
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
char filename[256][256];
int len = 0;
int trave_dir(char* path, int depth)
{
??? DIR *d; //聲明一個句柄
??? struct dirent *file; //readdir函數(shù)的返回值就存放在這個結(jié)構(gòu)體中
??? struct stat sb;???
???
??? if(!(d = opendir(path)))
??? {
??? ??? printf("error opendir %s!!!/n",path);
??? ??? return -1;
??? }
??? while((file = readdir(d)) != NULL)
??? {
??????? //把當前目錄.,上一級目錄..及隱藏文件都去掉,避免死循環(huán)遍歷目錄
??????? if(strncmp(file->d_name, ".", 1) == 0)
??? ??? ??? continue;
??????? strcpy(filename[len++], file->d_name); //保存遍歷到的文件名
??????? //判斷該文件是否是目錄,及是否已搜索了三層,這里我定義只搜索了三層目錄,太深就不搜了,省得搜出太多文件

??????? if(stat(file->d_name, &sb) >= 0 && S_ISDIR(sb.st_mode) && depth <= 3)
??????? {
??????????? trave_dir(file->d_name, depth + 1);
??????? }
??? }
??? closedir(d);
??? return 0;
}
int main()
{
??? int depth = 1;
??? int i;
??? trave_dir("/usr/keygoe/ini/", depth);
??? for(i = 0; i < len; i++)
??? {
??? ??? printf("%s/t", filename[i]);
??? }
??? printf("/n");
??? return 0;
}

總結(jié)

以上是生活随笔為你收集整理的linux opendir readdir closedir 的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。