用linuxC語言遍歷輸出文件目錄下的文件夾和文件


  • 實驗環境linux mint 開發平台 Qt5.11
  • 總體思想,linux C的文件目錄相關函數有 mkdir rmdir opendir readdir
  • 文件目錄指針類型 DIR*
  • dirent代表系統文件目錄相關的結構體,其中屬性d_type文件類型 d_name文件名或目錄名DT_DIR代表文件目錄,DT_REG代表普通文件
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<dirent.h>
#include<sys/types.h>

int getdir(char * pathname)
{
    DIR* path=NULL;
    path=opendir(pathname);

    if(path==NULL)
    {
        perror("failed");
        exit(1);
    }
    struct dirent* ptr; //目錄結構體---屬性:目錄類型 d_type,  目錄名稱d_name
    char buf[1024]={0};
    while((ptr=readdir(path))!=NULL)
    {
        if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0)
        {
            continue;
        }
        //如果是目錄
        if(ptr->d_type==DT_DIR)
        {

            sprintf(buf,"%s/%s",pathname,ptr->d_name);
            printf("目錄:%s\n",buf);
            getdir(buf);
        }
        if(ptr->d_type==DT_REG)
        {
            sprintf(buf,"%s/%s",pathname,ptr->d_name);//把pathname和文件名拼接后放進緩沖字符數組
            printf("文件:%s\n",buf);
        }
    }
    return 0;
}
int main()
{
    getdir("/home/cpc/Pictures");
    return 0;
}

 

輸出結果:


免責聲明!

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



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