gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > text filtering?

#135691 - spinal_cord - Wed Jul 25, 2007 5:13 pm

Just wondering, If I have a list of filenames char name[numfiles][maxnumchars], how do I go about filtering filenames by extension? so I could list only .txt file for example?
_________________
I'm not a boring person, it's just that boring things keep happening to me.
Homepage

#135706 - kusma - Wed Jul 25, 2007 6:02 pm

spinal_cord wrote:
Just wondering, If I have a list of filenames char name[numfiles][maxnumchars], how do I go about filtering filenames by extension? so I could list only .txt file for example?


use something like:
Code:
0 == strcmp(strrchr(name[i], '.'), ".txt")


to determine if the filename ends in ".txt". Read up on the functions used there, and keep in mind that you'll need some more glue-code to handle filenames without '.' in them.

#135720 - spinal_cord - Wed Jul 25, 2007 7:39 pm

Just had a quick google, for those terms. Am I right in thinking its comparing everything in the string after and including the '.' with '.txt'? seems straight forward. Thanks for the help.
_________________
I'm not a boring person, it's just that boring things keep happening to me.
Homepage

#135721 - kusma - Wed Jul 25, 2007 7:55 pm

spinal_cord wrote:
Am I right in thinking its comparing everything in the string after and including the '.' with '.txt'? seems straight forward

You are correct, sir. Here's a more complete example:

Code:
#include <string.h>

int isTxt(const char *filename)
{
   char *dotpos = strrchr(filename, '.');
   if (NULL == dotpos) return 0;
   
   return 0 == strcmp(dotpos, ".txt");
}

int main(int argc, const char *argv[])
{
   if (argc > 1) printf("%d\n", isTxt(argv[1]));
   return 0;
}

#135725 - spinal_cord - Wed Jul 25, 2007 8:15 pm

Things like this seemed a lot easier when I used to do them in BASIC :P
_________________
I'm not a boring person, it's just that boring things keep happening to me.
Homepage

#135796 - tepples - Thu Jul 26, 2007 12:49 pm

Then maybe you just need to try some different string handling libraries. Things like this were easy in BASIC because BASIC had garbage-collected strings and a few other niceties.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#135798 - kusma - Thu Jul 26, 2007 1:06 pm

..or try Python!
Code:
string[-4:] == ".txt"