// routine for loading all grass sprites we can find
char buffer[32];
std::string setname = "jungle";
int count = 0;
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
while (filesystem::exists(std::string(buffer))) // returns true if the file exists in folder
{
// load
// { ... }
// step
count++;
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
}
Refactorings
No refactoring yet !
bob
January 26, 2009, January 26, 2009 10:37, permalink
// routine for loading all grass sprites we can find
char buffer[32];
std::string setname = "jungle";
for (int count = 0; ; count++)
{
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
if (!filesystem::exists(std::string(buffer))) // returns true if the file exists in folder
break;
// load
// { ... }
}
// by the way, since you are using C++, you might consider using string streams instead of sprintf:
#include <sstream>
std::ostringstream o;
o << "grass_" << setname << "_" << count << ".png";
std::string filename = o.str();
Ants
January 26, 2009, January 26, 2009 10:37, permalink
How about this?
// routine for loading all grass sprites we can find
char buffer[32];
std::string setname = "jungle";
int count = 0;
while(true)
{
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
if(!filesystem::exists(std::string(buffer)))
break;
// load
// { ... }
// step
count++;
}
Adam
January 27, 2009, January 27, 2009 05:45, permalink
glob_t results;
std::string setname = "jungle";
std::stringstream pattern;
pattern << "grass_" << setname << "_[0-9]*.png";
glob(pattern.str().c_str(), GLOB_ERR, NULL, &results);
for (int i = 0; i < results.gl_pathc; i++) {
load(results.gl_pathv[i]);
}
globfree(&results);
Kartik Agaram
January 28, 2009, January 28, 2009 16:21, permalink
A function call makes it all clearer.
bool filenameExists(char* buffer, int count) {
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
return filesystem::exists(std::string(buffer));
}
char buffer[32];
std::string setname = "jungle";
int count = 0;
for (int count = 0; filenameExists(buffer, count); ++count) {
// load
// { ... }
}
Richard
February 5, 2009, February 05, 2009 17:11, permalink
I'd use boost::format() as a drop-in replacement for sprintf. sprintf_s is also MS specific, but boost::format works everywhere.
Nathan
February 6, 2009, February 06, 2009 14:25, permalink
And this is where do { ... } while is used!
// routine for loading all grass sprites we can find
char buffer[32];
std::string setname = "jungle";
int count = 0;
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
do
{
// load
// { ... }
// step
count++;
sprintf_s(buffer, 32, "grass_%s_%i.png\0", setname.c_str(), count);
} while (filesystem::exists(std::string(buffer)))] // returns true if the file exists in folder
Can this routine be done without the call to sprintf_s before the loop?