清泛IT社区
标题:
VC/Linux C++ 递归访问目录下所有文件
[打印本页]
作者:
清泛网
时间:
2016-02-29 15:23
标题:
VC/Linux C++ 递归访问目录下所有文件
VC函数,部分代码如下:
find(char * lpPath)
{
char szFind[MAX_PATH];
WIN32_FIND_DATA FindFileData;
strcpy(szFind,lpPath);
strcat(szFind,"\\*.*");
HANDLE hFind=::FindFirstFile(szFind,&FindFileData);
if(INVALID_HANDLE_VALUE == hFind) return;
while(TRUE)
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(FindFileData.cFileName[0]!='.')
{
strcpy(szFile,lpPath);
strcat(szFile,"\");
strcat(szFile,FindFileData.cFileName);
find(szFile);
}
}
else
{
cout << FindFileData.cFileName;
}
if(!FindNextFile(hFind,&FindFileData)) break;
}
FindClose(hFind);
}
复制代码
Linux C++实例如下:
#include <dirent.h>
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
void GetFileInDir(string dirName)
{
DIR* Dir = NULL;
struct dirent* file = NULL;
if (dirName[dirName.size()-1] != '/')
{
dirName += "/";
}
if ((Dir = opendir(dirName.c_str())) == NULL)
{
cerr << "Can't open Directory" << endl;
exit(1);
}
while (file = readdir(Dir))
{
//if the file is a normal file
if (file->d_type == DT_REG)
{
cout << dirName + file->d_name << endl;
}
//if the file is a directory
else if (file->d_type == DT_DIR && strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
{
GetFileInDir(dirName + file->d_name);
}
}
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
cerr << "Need Directory" << endl;
exit(1);
}
string dir = argv[1];
GetFileInDir(dir);
}
复制代码
欢迎光临 清泛IT社区 (https://bbs.tsingfun.com/)
Powered by Discuz! X3.3