c++ - 在 C++ 中从目录中列出文件时出错

标签 c++ directory

我的代码有问题。每当我运行该程序时,最后的文件搜索都会在不应该返回零值的地方返回零值。

代码如下:

#include <vector>
#include <string>
#include <windows.h>
#include <stdio.h>
#include <iostream> 
#include <conio.h>

using namespace std;

string GetPath(string path){
        char directory[1024];
        vector <string> filelist;
        strcpy_s(directory,path.c_str());
        BOOL checker;

            WIN32_FIND_DATA findFileData;
            HANDLE hFind = FindFirstFile((LPCSTR)directory, &findFileData);
            cout <<"Files in:" <<"\n"<<directory<<"\n"<<endl;
            checker = FindNextFile(hFind, &findFileData);

            while(checker)
            {
                checker = FindNextFile(hFind, &findFileData);
                filelist.push_back(findFileData.cFileName);//save file list in vector
                cout << findFileData.cFileName << endl;
            }

            DWORD error = GetLastError();
            if( error != ERROR_NO_MORE_FILES)
            {

            }
            /*for (unsigned i=1;i<filelist.size();i++){
                cout << filelist[i]<<endl;//print out the vector
            }*/


            return 0;
}

int main()
{
   string path;
   path="C:\\Program Files\\*.*";
   vector <string> handler;
   path = GetPath(path);
}

最佳答案

试试这个作为完整性检查:

#include <tchar.h>
#include <stdexcept>
#include <vector>
#include <string>
#include <iostream>
#include <windows.h>

#ifdef UNICODE
typedef std::wstring tstring;
static std::wostream& tcout = std::wcout;
#else
typedef std::string tstring;
static std::ostream& tcout = std::cout;
#endif

std::vector<tstring> GetPath(tstring const& path)
{
    WIN32_FIND_DATA findFileData;
    HANDLE const hFind = FindFirstFile(path.c_str(), &findFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        throw std::runtime_error(""); // realistically, throw something useful

    std::vector<tstring> filelist;
    do filelist.push_back(findFileData.cFileName);
    while (FindNextFile(hFind, &findFileData));
    FindClose(hFind);
    if (GetLastError() != ERROR_NO_MORE_FILES)
        throw std::runtime_error(""); // realistically, throw something useful
    return filelist;
}

int _tmain()
{
    std::vector<tstring> files = GetPath(_T("C:\\Program Files\\*.*"));
    for (std::vector<tstring>::const_iterator iter = files.begin(), iter_end = files.end(); iter != iter_end; ++iter)
        tcout << *iter << _T('\n');
}

如果有效,清理错误处理逻辑并使用它;-]。如果不是,那么@young 是正确的,你有本地化问题;更改您的项目设置以使用 Unicode 作为字符集,它应该可以工作。

关于c++ - 在 C++ 中从目录中列出文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5151622/

相关文章:

.net - ClickOnce 无法查看在 PostBuild 事件期间复制的文件

c++ - 如何从以 shared_ptr 为键的 unordered_set 中获取基于 raw_ptr 的元素

c++ - 虚函数的不同返回类型

c++ - 在 O(log n) 时间复杂度中查找排序数组中的多数元素

Java.nio : most concise recursive directory delete

javascript - 在 JS 文件中找不到配置目录

c++ - 如何使用 stoi() 将字符串转换为整数?

c++ - 用于序列化目的的 SQLite3

java - 如何使用 spring-batch 和 MultiResourceItemReader 读取文件夹中的所有文件?

c - 这个循环有问题吗?