linux下目录操作

1. 常用函数

 

#include <dirent.h>
//open a directory
//failed-NULL, other-return a DIR stream
DIR *opendir (const char* path_name);

//close the directory stream
//0 succeed, -1 not
int closedir(DIR* dir_ptr);

//read a dir entry from dir_ptr
//NULL for EOF or error
dirent* readdir(DIR* dir_ptr);


2.实例

读取当前目录下的普通文件

 

#include <dirent.h>

#include <iostream>
using namespace std;

int main()
{
    DIR* dir_ptr = NULL;
    dirent* entry = NULL;
    dir_ptr = opendir("./");
    if (NULL == dir_ptr)
    {   
        return -1; 
    }   

    while (NULL != (entry = readdir(dir_ptr)))
    {   
        if (entry->d_type != DT_DIR)
        {   
            cout << "get a file:" << entry->d_name << endl;
        }   
    }   

    closedir(dir_ptr);
    return 1;
}


 

posted @ 2013-11-21 17:33  春文秋武  阅读(185)  评论(0编辑  收藏  举报