将文件夹中的所有文件名存储到向量中

时间:2019-05-07 18:19:30

标签: c++ winapi

此代码。一切正常,但是例如当我尝试退出时:

cout << getAllSongs("path\\*")[1]

输出为空,不显示任何内容

vector<string> getAllSongs(string path) {
    // can queue up up to 1000 melodii
    vector<string> songList(1000);

    WIN32_FIND_DATA FindFileData;
    string all = path;
    HANDLE hFind = FindFirstFile(all.c_str(), &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) {
        cout << hFind;
        cout << "there is a handle problem";
        exit(-1);
    }
    else do {
        //cout << FindFileData.cFileName << endl; this works
        songList.push_back(FindFileData.cFileName);
    } while (FindNextFile(hFind, &FindFileData));
    FindClose(hFind);

    return songList;    
}

1 个答案:

答案 0 :(得分:1)

无论文件夹中实际上有什么内容,您总是在向量中预先填充1000个空字符串,然后添加从索引1000开始的文件名。因此,keyup处的字符串始终为空。

请尝试以下类似操作:

vector[1]
vector<string> getAllSongs(string path) {
    // can queue up up to 1000 melodii

    //vector<string> songList(1000); // <-- DO NOT create 1000 empty strings!
    vector<string> songList;
    songList.reserve(1000); // <-- DO THIS instead!

    WIN32_FIND_DATAA FindFileData;
    HANDLE hFind = FindFirstFileA(path.c_str(), &FindFileData); // <-- use the ANSI function explicitly!
    if (hFind == INVALID_HANDLE_VALUE) {
        if (GetLastError() != ERROR_FILE_NOT_FOUND) { // <-- ADD error checking...
            cout << "there is a problem with the search!";
        }
    }
    else {
        do {
            if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { // <-- ADD type checking...
                //cout << FindFileData.cFileName << endl; this works
                songList.push_back(FindFileData.cFileName);
            }
        }
        while (FindNextFileA(hFind, &FindFileData)); // <-- use the ANSI function explicitly!

        if (GetLastError() != ERROR_NO_MORE_FILES) { // <-- ADD error checking...
            cout << "there is a problem with the search!";
        }

        FindClose(hFind);
    }

    return songList;    
}