如何列举一个目录下的文件
飘飘白云 2008.04.04
取得一个目录路径之后,使用FindFirstFile与FindNextFile就可以列举该目录的所有子目录以及所有文件。下面贴段列举指定目录下所有特定后缀(.txt)文件。
1void getTxtFileByDirectory(const CStringW& dirPath)
2{
3 nutVec.clear();
4 path = dirPath;
5
6 WIN32_FIND_DATA ffd;
7 LARGE_INTEGER filesize;
8 HANDLE hFind;
9
10 CStringW nutFile;
11 nutFile.Format(L"%s\\*.txt", path);
12
13 // Check that the input path plus 2 is not longer than MAX_PATH.
14 size_t length;
15 StringCchLength(nutFile, MAX_PATH, &length);
16
17 if (length > (MAX_PATH - 2)) {
18 CStringW dbgInfo;
19 dbgInfo.Format(L"Directory %s is too long!\n", path);
20 OutputDebugString(dbgInfo);
21 return;
22 }
23
24 hFind = FindFirstFile(nutFile, &ffd);
25 if (hFind == INVALID_HANDLE_VALUE) {
26 return;
27 }
28
29 do {
30 filesize.LowPart = ffd.nFileSizeLow;
31 filesize.HighPart = ffd.nFileSizeHigh;
32
33 CStringW dbgInfo;
34 dbgInfo.Format(L" %s %ld bytes\n", ffd.cFileName, filesize.QuadPart);
35 OutputDebugString(dbgInfo);
36
37 nutVec.push_back(ffd.cFileName);
38 } while (FindNextFile(hFind, &ffd) != 0);
39
40 FindClose(hFind);
41}
调用该函数之后,output窗口输出文件名以及文件大小信息:
0000000000000001.txt 365 bytes
0000000000000002.txt 494 bytes
0000000000000003.txt 352 bytes
0000000000000004.txt 468 bytes
0000000000000005.txt 366 bytes
0000000000000006.txt 461 bytes
0000000000000007.txt 375 bytes
000000000000000a.txt 375 bytes
000000000000000b.txt 382 bytes
关于路径的取得,可以使用打开文件对话框获得,相应代码如下:
1 OPENFILENAMEW ofn; // common dialog box structure
2 wchar_t szFile[260]; // buffer for file name
3 ZeroMemory(&ofn, sizeof(ofn));
4 ofn.lStructSize = sizeof(ofn);
5 ofn.hwndOwner = NULL;
6 ofn.lpstrFile = szFile;
7 ofn.lpstrTitle = L"Select a nut file to set a directory for auto load";
8 ofn.lpstrFile[0] = L'\0';
9 ofn.nMaxFile = sizeof(szFile);
10 ofn.lpstrFilter = L"nut\0*.nut";
11 ofn.nFilterIndex = 1;
12 ofn.lpstrFileTitle = NULL;
13 ofn.nMaxFileTitle = 0;
14 ofn.lpstrInitialDir = path;
15 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
16
17 // Open file dialog box.
18 if (GetOpenFileNameW(&ofn) == TRUE) {
19 if (ofn.lpstrFile) {
20 size_t len = wcslen(ofn.lpstrFile);
21 szFile[len] = L'\0';
22
23 CStringW fullPath;
24 fullPath.Format(L"%s", szFile);
25
26 HLUint32 n = fullPath.ReverseFind(L'\\');
27 if (n > 0) {
28 path = fullPath.Left(n);
29 }
30 }
31 }