window下,遍历目录主要是用FindFirstFile和FindNextFile,而linux下是用opendir和readdir实现
void scanFile(char *szDir)
{
WIN32_FIND_DATA FindFileData;
char szFilePath[MAX_PATH];
strncpy(szFilePath, szDir, strlen(szDir) + 1);
strncat(szFilePath, "*", 2);
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = FindFirstFile(szFilePath, &FindFileData);
if (hFile == INVALID_HANDLE_VALUE) {
printf("FindFirstFile error\n");
return ;
}
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (strcmp(FindFileData.cFileName, ".") != 0
&& strcmp(FindFileData.cFileName, "..") != 0) {
char tmpPath[MAX_PATH];
strncpy(tmpPath, szDir, strlen(szDir) + 1);
strncat(tmpPath, FindFileData.cFileName, strlen(FindFileData.cFileName) + 1);
strncat(tmpPath, "\\", 2);
scanFile(tmpPath);
}
} else {
printf("path:%s fileName=%s\n", szDir, FindFileData.cFileName);
}
while (FindNextFile(hFile, &FindFileData) != 0) {
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (strcmp(FindFileData.cFileName, ".") != 0
&& strcmp(FindFileData.cFileName, "..") != 0) {
char tmpPath[MAX_PATH];
strncpy(tmpPath, szDir, strlen(szDir) + 1);
strncat(tmpPath, FindFileData.cFileName, strlen(FindFileData.cFileName) + 1);
strncat(tmpPath, "\\", 2);
scanFile(tmpPath);
}
} else {
printf("path:%s fileName=%s\n", szDir, FindFileData.cFileName);
}
}
FindClose(hFile);
}
linux下遍历 代码如下:
void scanFile(char *szDir)
{
DIR *pDir = NULL;
struct dirent *pFile = NULL;
pDir = opendir(szDir);
if (pDir == NULL) return;
while ((pFile = readdir(pDir)) != NULL) {
if (pFile->d_type & DT_DIR) {
if (strcmp(pFile->d_name, ".") == 0
|| strcmp(pFile->d_name, "..") == 0) continue;
char Path[256];
int len = strlen(szDir);
strncpy(Path, szDir, len + 1);
if (szDir[len - 1] != '/') strncat(Path, "/", 2);
strncat(Path, pFile->d_name, strlen(pFile->d_name) + 1);
scanFile(Path);
} else {
printf("path:%s fileName:%s\n", szDir, pFile->d_name);
}
}
closedir(pDir);
}