windows下使用C/C++怎么遍历目录并读取目录下的文件列表?


linux 平台可以有 dirent 库来帮助实现,在 windows 下呢?

---更新于2015-05-19 00:13---
目前得到了多种解决方案,挨个尝试后会把自己的解决方案也贴出来。感谢各位大神的热情帮助!不胜感激

---更新于2015-05-19 13:00--
贴上了自己的方法,各位大神的回答都很感激,不过工作较忙还没来得及一一验证,请看到的小伙伴用到了自己验证一下吧!就采纳回答的最详细的@pezy大神的回答吧!

c 文件读取 C++ windows

含巨大长茎 9 years, 11 months ago

有一种取巧的方法,就是用system指令:


 dir > filelist.txt

然后读取文件解析。

HIGHKGB answered 9 years, 11 months ago

这里贴上我的一种方法,使用的是 MFC 提供的 CFileFind 类,依赖 afx.h 库文件,跟 msdn 的示例代码差不多,只不过我这里用一个 vector 保存了一下取到的文件列表。代码写的比较乱,权且提供一种方法。

void list_files(vector & files_arr, LPCTSTR pstr) {
    CFileFind finder;
    CStringW strWildcard(pstr);
    strWildcard += _T("\\*.*");
    BOOL bWorking = finder.FindFile(strWildcard);
    while (bWorking) {
        bWorking = finder.FindNextFile();
        if (finder.IsDots()) {
            continue;
        }
        if (finder.IsDirectory()) {
            CStringW str = finder.GetFilePath();
            //TRACE(_T("%s\n"), (LPCTSTR)str);
            list_files(files_arr, str);
        } else {
            CStringW str = finder.GetFilePath();
            files_arr.push_back(str);
        }
    }
    finder.Close();
}
Fench answered 9 years, 11 months ago

可以用io.h这个库


 #include <iostream>
#include <io.h>
#include <string>

using namespace std;

void dir(string path)
{
    long hFile = 0;
    struct _finddata_t fileInfo;
    string pathName, exdName;

    if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) {
        return;
    }
    do {
        cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR? "[folder]":"[file]") << endl;
    } while (_findnext(hFile, &fileInfo) == 0);
    _findclose(hFile);
    return;
}

int main()
{
    string path="G:\\testdir";
    dir(path);
    return 0;
}

开着飞机打飞机 answered 9 years, 11 months ago

boost的filesystem库满足你!

ERO三号机 answered 9 years, 11 months ago

Windows 下最本质的做法,是直接调用 Windows API,解决你的这个问题,需要三个 API 函数:

应该基本上可以顾名思义了吧。

核心用法如下:


 HANDLE hFind = FindFirstFile(szDir, &ffd);

// List all the files in the directory with some info about them.
do
{
   if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
   {
      _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
   }
   else
   {
      filesize.LowPart = ffd.nFileSizeLow;
      filesize.HighPart = ffd.nFileSizeHigh;
      _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
   }
}
while (FindNextFile(hFind, &ffd) != 0);

FindClose(hFind);

更加完整的实例代码可以参考这里: Listing the Files in a Directory


优势在于不需要任何第三方库,可以获得其他更多文件的信息,譬如想知道文件的修改时间之类的,也可以在这上面扩展。

唯一的劣势,应该就是无法直接跨平台,但可以通过 一式两份 的方式跨,要更加高效。


如果想直接跨平台,即 Linux 与 Windows 下使用同一份代码,还可以考虑使用 Qt 框架。 QDir 可以以最清晰简单的代码解决上述问题:


 // lists all the files in the current directory
#include <QDir>
#include <iostream>

 int main(int argc, char *argv[])
 {
     QCoreApplication app(argc, argv);
     QDir dir;
     dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
     dir.setSorting(QDir::Size | QDir::Reversed);

     QFileInfoList list = dir.entryInfoList();
     std::cout << "     Bytes Filename" << std::endl;
     for (int i = 0; i < list.size(); ++i) {
         QFileInfo fileInfo = list.at(i);
         std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));
         std::cout << std::endl;
     }
     return 0;
 }

超电磁兄贵 answered 9 years, 11 months ago

Your Answer