SFML community forums

Help => General => Topic started by: mercender on February 01, 2017, 03:51:20 pm

Title: Loading all png files from a folder?
Post by: mercender on February 01, 2017, 03:51:20 pm
Hi,
My application (c++/sfml) needs a lot of separate images. I have a folder of 17 png images, with potentially more to be added. I want my program to load all the images from a folder in my app directory into a vector in chronological order (1,2 etc). I have only ever loaded the images into a texture data type individually, which means going into the code every time one is added. (I am using this program to visualize a bunch of images). I plan on adding up to 40 or more, so this is not very intuitive. The code already handles each texture.

What's the best way to implement this? I am having a hard time finding solutions on the internet.
Title: Re: Loading all png files from a folder?
Post by: JayhawkZombie on February 01, 2017, 05:08:14 pm
Why not use a textures.txt file or something?
Just edit the file whenever you want to change textures.  It'll remove a platform-dependent filesystem API usage.
Kinda like this?

texture1.png
someothertexture.png
somethingelse.png
...

Then in your code:

std::string filename{ "" };
std::ifstream file("path_to_textures.txt");

while (file >> filename) {
    my_textures.push_back({});
    if (!my_textures.back().loadFromFile(filename))
        report error
}
Title: Re: Loading all png files from a folder?
Post by: mercender on February 01, 2017, 05:11:21 pm
Why not use a textures.txt file or something?
Just edit the file whenever you want to change textures.  It'll remove a platform-dependent filesystem API usage.
Kinda like this?

texture1.png
someothertexture.png
somethingelse.png
...

Then in your code:

std::string filename{ "" };
std::ifstream file("path_to_textures.txt");

while (file >> filename) {
    my_textures.push_back({});
    if (!my_textures.back().loadFromFile(filename))
        report error
}

Cool solution, although it still requires some effort from the user. I think it's worth it though. Will try when I get the chance, many thanks!
Title: Re: Loading all png files from a folder?
Post by: fallahn on February 01, 2017, 05:36:29 pm
If your compiler supports C++17 filesystem functions are now part of the standard (which you can see here (http://en.cppreference.com/w/cpp/filesystem)). Slightly older compilers may also provide access via the experimental namespace, and they are all available as part of boost, upon which the std version is based. You can use file_time_type (http://en.cppreference.com/w/cpp/filesystem/file_time_type) to sort the files chronologically.