码迷,mamicode.com
首页 > 系统相关 > 详细

Linux下扫描目录把所有的普通文本列入列表里面

时间:2014-09-09 19:48:29      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   div   sp   log   on   c   amp   

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
const static int STRARRAYLEN=256;
typedef char StringBuffer[STRARRAYLEN];
typedef struct StringList_t StringList;

struct StringList_t{
    StringBuffer sb;
    StringList *next;

    StringList_t() {
        next = 0;
        memset(sb, 0, sizeof (sb)); //sb[0]=‘\0‘;
    }

    ~StringList_t() {
        StringList *itor = this->next;
        while (itor != NULL) {
            this->next = itor->next;
            delete itor;
            itor = this->next;
        }
    }
};
void OutputList(StringList *list) {
    StringList *itor = list;
    while (itor != 0) {
        printf("%s\n", itor->sb);
        itor = itor->next;
    }
}
int ScanFilesToList(char* folderPath, StringList *fileList) {
    
    //get rid of ‘/‘ within folderPath
    int slen = strlen(folderPath);
    if (folderPath[slen - 1] == ‘/‘) {
        folderPath[slen - 1] = ‘\0‘;
    }
    StringBuffer pwd = "";
    getcwd(pwd, sizeof (pwd));
    if (strncmp(folderPath, "..", 2) == 0) {
        char pwdbak[200] = "";
        strcpy(pwdbak, pwd);
        chdir(folderPath);
        memset(pwd, 0, sizeof (pwd));
        getcwd(pwd, sizeof (pwd));
        strcpy(folderPath, pwd);
        strcpy(pwd, pwdbak);
    } else {
        chdir(folderPath);
    }
    DIR *dir = opendir(folderPath);
    if (dir == NULL) {
        printf("failed to open dir <%s> \n", folderPath);
    }
    struct dirent *dt = NULL;
    struct stat statbuf;
    while (dt = readdir(dir)) {
        if (‘.‘ == dt->d_name[0]) {
            continue;
        }
        lstat(dt->d_name, &statbuf);
        if (S_ISDIR(statbuf.st_mode)) {
            StringBuffer sb = "";
            sprintf(sb, "%s/%s", folderPath, dt->d_name);
            chdir(sb);
            ScanFilesToList(sb, fileList);
            chdir("..");
        } else if (S_ISREG(statbuf.st_mode)) {
            //addfiles to list
            StringList *tmp=new StringList;
            sprintf(tmp->sb,"%s/%s", folderPath, dt->d_name);
            tmp->next=fileList->next;
            fileList->next=tmp;
        }
    }
    chdir(pwd);
    return 0;
}

Linux下扫描目录把所有的普通文本列入列表里面

标签:blog   io   ar   div   sp   log   on   c   amp   

原文地址:http://www.cnblogs.com/jealdean/p/3963085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!