VC/Linux C++ 递归访问目录下所有文件
清泛原创
VC函数,部分代码如下:
Linux C++实例如下:
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);
}
上一篇:std::vector排序
下一篇:c++ boost::multi_index composite keys efficiency