Linux C :遍歷輸出指定目錄下的所有文件


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

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

readdir函數的原型為:
struct dirent *readdir(DIR *dir);
看它的參數就知道該參數是opendir函數返回的句柄,而該函數的返回值是struct dirent* 類型,這里我們必須了解一下這個結構體:
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 */
};
這個結構體的d_name存放的就是文件的名字,這里的文件包括普通文件,目錄文件等等,在linux的思想中,所有的東西都是文件。

closedir函數的原型為:
int closedir(DIR *dir);
這個函數就不用多說了,一般有開(open),就有關(close),這樣的結構經常可出看到,如fopen,fclose等等。

三個函數介紹完了,直接來一個例子吧:
**********************************************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函數的返回值就存放在這個結構體中
    struct stat sb;   
   
    if(!(d = opendir(path)))
    {
        printf("error opendir %s!!!/n",path);
        return -1;
    }
    while((file = readdir(d)) != NULL)
    {
        //把當前目錄.,上一級目錄..及隱藏文件都去掉,避免死循環遍歷目錄
        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;
}
*****************************************************************************************************************
Linux C :遍歷輸出指定目錄下的所有文件 - myswirl - myswirl
 
  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM