1.遍歷Unix目錄code
int traverse(const char *current_path) { struct stat st; int ret = stat(current_path, &st); if (ret != 0) { return -1; } char path[512] = {0}; if (S_ISDIR(st.st_mode)) { DIR *dir = opendir(current_path); if (NULL == dir) { return -1; } struct dirent *ptr = NULL; while((ptr = readdir(dir)) != NULL) { if(strstr(ptr->d_name, ".") == ptr->d_name) { continue; } snprintf(path, sizeof(path), "%s/%s", current_path, ptr->d_name); traverse(path); } closedir(dir); } else { printf("%s\n", path); } return 0; }
非遞歸實現遞歸
int traverse(const char *path) { struct dirent *entry = NULL; DIR *dir = NULL; std::stack<std::string> ss; ss.push(path); while(!ss.empty()) { std::string child = ss.top(); ss.pop(); dir = opendir(child.c_str()); if (NULL == dir) { printf("@error:%s, %d, %s\n", child.c_str(), ss.size(), strerror(errno)); return -1; } for(int i = 0; i < 10000 && ((entry = readdir(dir)) != NULL); i++) { if (strstr(entry->d_name, ".") == entry->d_name) { continue; } if (strstr(entry->d_name, "Application Support")) { continue; } if (entry->d_type == DT_DIR) { char str[1024] = {0}; snprintf(str, sizeof(str), "%s/%s", child.c_str(), entry->d_name); ss.push(str); } else { printf("file:%s\n", entry->d_name); } } closedir(dir); } return 0; }
2.遍歷Windows目錄string
int traverse(TCHAR *szDir) { TCHAR path[MAX_PATH] = { 0 }; WIN32_FIND_DATA ffd = {0}; HANDLE hFind = INVALID_HANDLE_VALUE; hFind = FindFirstFile(szDir, &ffd); while (FindNextFile(hFind, &ffd) != 0) { sprintf_s(curPath, "%s\\%s", dir, ffd.cFileName); if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) { continue; } int ret = traverse(path); if (ret != 0 ) { FindClose(hFind); return -1; } } else { //文件 } } FindClose(hFind); return 0; }