Linux遍历文件夹下文件

用stat函数判断文件类型。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h> 
#include <dirent.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sstream>
using namespace std;

int main(int argc, char const *argv[]) 
{ 
    if(argc != 2)
    {
        printf("input dirent\n");
        return -1;
    }
    struct dirent *pDirEntry = NULL;
    DIR *pDir = NULL;
    if((pDir = opendir(argv[1])) == NULL)
    {
       printf("cannot open dirent %s\n", argv[1]);
       return -1;
    }
    while(pDirEntry = readdir(pDir))
    {   
        if (strcmp(pDirEntry->d_name, ".") == 0 || strcmp(pDirEntry->d_name, "..") == 0)
        {
            continue;
        }

        string file_name = pDirEntry->d_name;
        string::size_type pos = file_name.find('.');
        if(pos != string::npos)
        {   
            //文件后缀名
            string extension = file_name.substr(pos + 1);
            printf("%s extension is %s\n", pDirEntry->d_name, extension.c_str());
        }

        stringstream ss;
        ss<<argv[1]<<pDirEntry->d_name;

        struct stat buf; 
        stat(ss.str().c_str(), &buf); 
        if(S_IFDIR & buf.st_mode){
            printf("%s is folder\n", pDirEntry->d_name);
        }else if(S_IFREG & buf.st_mode){ 
            printf("%s is file\n", pDirEntry->d_name);
        }
    }

    return 0; 
}

你可能感兴趣的:(Linux遍历文件夹下文件)