遍历目录所有文件
原创,转载时请注明,谢谢。邮箱:tangzhongp@163.com
博客园地址:http://www.cnblogs.com/embedded-tzp
Csdn博客地址:http://blog.csdn.net/xiayulewa
Linux C : readdir
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main(){
DIR *dir_p = opendir("/");
if(dir_p == NULL) perror("opendir"), exit(-1);
struct dirent *ent;
while(1){
ent = readdir(dir_p);
if(ent == NULL) break;
//打印子项类型和子项名
if( 0 == strcmp(ent->d_name, ".")
|| 0 == strcmp(ent->d_name, "..")){
continue;
}
printf("%d, %s\n", ent->d_type, ent->d_name);
//type == 4 是目录,其他是文件
}
}
Linux C: scandir
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int dir_printall(const char *pathname)
{
struct dirent **namelist = NULL;
int ent_n;
int i;
ent_n = scandir(pathname, &namelist, NULL, alphasort);
if (ent_n < 0){
printf("scandir() fail : %s\n", pathname);
return -1;
}
for(i = 0; i < ent_n; i++){
if( 0 == strcmp(namelist[i]->d_name, ".")
|| 0 == strcmp(namelist[i]->d_name, "..")){ // skip parent dir and self
continue;
}
char path_buf[512] = {0}; // use malloc will be bettor
sprintf(path_buf, "%s/%s", pathname, namelist[i]->d_name);
printf("%s\n", path_buf);
if(4 == namelist[i]->d_type){ // 4 means dir
int retval = dir_printall( path_buf); // recurrence call
if(-1 == retval){
fprintf(stderr, "dir_printall() fail: %s\n", path_buf);
continue;
//goto out; // not end, for /proc/5236/net can't
}
}
}
out:
for(i = 0; i < ent_n; i++){
if(namelist[i]){
free(namelist[i]);
namelist[i] = NULL;
}
}
if(namelist){
free(namelist);
namelist = NULL;
}
return 0;
}
int main(void)
{
if (-1 == dir_printall("/")){
perror("dir_printall()");
}
return 0;
}
C++
shell
#带完整路径
file=$(find ./)
echo $file
#只有文件名
file=$(ls -R)
echo $file
qt
自己做的项目中拷贝出来的一段简化的代码。
bool SearchThread::createDb()
{
qDebug() << __LINE__ << __FUNCTION__;
QFileInfoList fileDriveList = QDir::drives(); // 获取盘符,windows下为c:, d:, e:, linux下为 /
foreach(QFileInfo fileDrive, fileDriveList){ // 循环处理盘符
qDebug() << fileDrive.absoluteFilePath();
createDb(fileDrive.absoluteFilePath());
}
return true;
}
bool SearchThread::createDb(const QString &filePath)
{
QDir dir = filePath;
const QDir::Filters FILTERS = QDir::AllDirs | QDir::Files | QDir::Drives
| QDir::NoDotAndDotDot | QDir::Hidden | QDir::System;
QFileInfoList fileInfoList = dir.entryInfoList(FILTERS, QDir::DirsFirst | QDir::Name);
foreach(QFileInfo fileInfo, fileInfoList){
bool isdir = fileInfo.isDir();
if(isdir){
if(!fileInfo.isSymLink()){ // 不是链接文件,防止死循环
createDb(fileInfo.absoluteFilePath());
}
}
}
return true;
}