c++ - 查找文件夹中所有文件的文件路径

标签 c++ file-io sdl

我正在尝试使用 SDL 将一堆图像转换为纹理。到目前为止,我知道可以手动完成所有操作:

//Load front alpha texture
    if (!gModulatedTexture.loadFromFile("14_animated_sprites_and_vsync/text2.png"))
    {
        printf("Failed to load front texture!\n");
        success = false;
    }
    else
.....

但是,我有很 multimap 像要加载,所以我正在寻找一种自动化流程的方法。我想将所有图像放入一个文件夹中,然后执行以下操作:

i=0
while (there are still images to load) {
     textureBank[i] = current image
     i++
}

我在想可能有一些简单的方法可以只读取目录中所有文件的文件路径,但我一直没能找到一种方法来做到这一点。

有什么建议吗?

最佳答案

您不需要使用任何第 3 方库,例如 boost ,只需调用以下函数(适用于 Windows 操作系统)。在此之后,您将获得给定文件夹内的所有文件路径 vector<string> .

#include <Windows.h>
// folder must end with "/", e.g. "D:/images/"
vector<string> get_all_files_full_path_within_folder(string folder)
{
    vector<string> names;
    char search_path[200];
    sprintf(search_path, "%s*.*", folder.c_str());
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path, &fd); 
    if(hFind != INVALID_HANDLE_VALUE) 
    { 
        do 
        { 
            // read all (real) files in current folder, delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) 
            {
                names.push_back(folder+fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd)); 
        ::FindClose(hFind); 
    } 
    return names;
}

关于c++ - 查找文件夹中所有文件的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860822/

相关文章:

c++ - SDL Console 输出在调试时有效,但在使用 exe 运行时无效

c - sdl2 SDL_Quit() 段错误

c++ - poll() 捕获线程返回值

java - BufferedInputStream.read(byte[]) 导致问题。以前有人遇到过这个问题吗?

C 通过读取系统调用在我的缓冲区中查找换行符

c - 如何使用 pebble c 读取文件?

opengl - SDL/OpenGL 纹理透明度

c++ - 遇到宽字符后文件被截断

c++ - C++中根据特定类型执行代码

c++ - 存储一组非重叠范围并严格查找值是否存在于任何一个范围中