Linux 系统编程--查看目录文件

来源:互联网 发布:淘宝店铺的模板怎么做 编辑:程序博客网 时间:2024/06/06 03:38

1、打印目录下所有文件及文件夹

#include <stdio.h>#include <unistd.h>#include <errno.h>#include <sys/stat.h>#include <sys/types.h>#include <dirent.h>int main(int argc,char **argv){    DIR* pDir;    struct dirent* pDirInfo;    if (argc == 2)    {        if (0 != chdir(argv[1]))        {            printf ("error num is : %d\n",errno);            switch(errno)            {            case EACCES:                printf("search permission is denied for one of the components  of  path\n");                break;            case EIO:                printf ("I/O error occurred\n");                break;            case ENOENT:                printf("No such file or directory\n");                break;            case EPERM:                printf ("Operation not permitted\n");                break;            }            return errno;        }        pDir = opendir(argv[1]);    }    else    {           pDir = opendir(".");    }    //打印当前目录            printf ("current directory is : %s\n",getcwd(NULL,0));    if (NULL == pDir)    {        perror("open dir failed !");        return -1;    }    pDirInfo = readdir(pDir);    while (pDirInfo)    {        printf("--------------------------------\n");        printf("name: %s \n",pDirInfo->d_name);        pDirInfo = readdir(pDir); //遍历文件夹    }    closedir(pDir);    return 0;}

2、遍历文件夹内容,包括子文件夹

//以树形结构的形式打印指定目录下的所有文件#include <unistd.h>#include <stdio.h>#include <dirent.h>#include <string.h>#include <sys/stat.h>#include <stdlib.h>#include <errno.h>void printDir1(const char * path, unsigned int depth);int main(int argc, char * *argv){    char *topDir = getcwd(NULL, 0);    if (argc == 2)    {        topDir = argv[1];    }    printf("遍历的目录为: %s\n", topDir);    printDir1(topDir, 0);    return 0;}void printDir1(const char * path, unsigned int depth){        DIR *pDir = opendir(path);    if (NULL == pDir)    {        perror("路径打开失败!");        return;    }    struct dirent *entry;    struct stat statbuf;    chdir(path);    char *curPath = getcwd(NULL,0);    if (!curPath)    {        perror("curPath == NULL ");        return;    }    while (NULL != (entry = readdir(pDir)))    {        stat(entry->d_name,&statbuf);        char *desPath = (char*)malloc(strlen(curPath) + strlen(entry->d_name) + 2);        sprintf(desPath,"%s/%s",curPath,entry->d_name);        if (S_ISDIR(statbuf.st_mode))        {            if ((strcmp(".",entry->d_name) == 0) || (strcmp("..",entry->d_name) == 0))                continue;            printf("%d级--这是目录: %s\n",depth,desPath);            printDir1(desPath,depth+1);        }        else        {            printf("%d级--这是文件: %s\n",depth,desPath);        }        free (desPath);    }    chdir("..");    closedir(pDir);    printf("\t*****%d级目录%s--遍历完成**********\n",depth,path);}