Archived

This topic is now archived and is closed to further replies.

DarkKiller

Simple string operations?

Recommended Posts

I''m working on a learning by doing opengl-c++ engine and I have to know how I can check whether a file is a jpg or a bitmap reading the extensions. in vb is made by calling right$(filename,len(filename),3). filename is clear. len gives the length of the string and 3 is the number of characters to get from the right. who can I get those with c++?

Share this post


Link to post
Share on other sites
In C:

  
const char *GetFileExtension(const char *filepath) {
int found_period = 0;

for( ; *filepath != ''\0''; ++filepath) {
if(*filepath == ''.'') {
found_period = 1;
break;
}
}
if(found_period == 0) return NULL;

while(*filepath != ''\0'') ++filepath;
while(*filepath != ''.'') --filepath;

return &filepath[1];
}

Returns NULL on failure.

Share this post


Link to post
Share on other sites
ok, the function works but I still have a problem with it.

When I use

MessageBox(NULL, GetFileExtension(strFileName), "CreateTexture", MB_OK);

to print the extension "jpg" appears without the quotation marks.
Thats fine. But when I try to compare GetFileExtension(strFileName) with "jpg" I get wrong results.

if (GetFileExtension(strFileName)=="jpg")
{
MessageBox(NULL, "Works", "Create Tex", MB_OK);
}
else
{
MessageBox(NULL, "Doesn''t Work", "Create Tex", MB_OK);
}

Share this post


Link to post
Share on other sites
You can clearly see you have a VB background

Use the strncmp() function,.. it compares two strings of characters with a fixed length. It returns zero if the strings are equal...


if ( strncmp( GetFileExtension(strFileName), "jpg", 3 ) == 0 )
{
MessageBox(NULL, "Works", "Create Tex", MB_OK);
} else
{
MessageBox(NULL, "Doesn't Work", "Create Tex", MB_OK);
}

You can't compare two strings directly in C/C++, you will end up comparing the addresses..

-Crawl

[edited by - Crawl on June 10, 2002 6:39:03 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
you can also find the extension like this...

void LoadTexture(char *filename)
{
char *Ext;
Ext = strchr(filename, ''.'');
Ext++;
strupr(Ext);
if((strcmpi(Ext,"BMP" == 0))
LoadBMP(...);
...
}

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
...
Ext = strchr(filename, '.');
...



you need to use strrchr, otherwise you get bad results for eg.
manRunning.1.jpg

also, don't rely on the extension being 3 characters, some people use .jpeg

[edited by - dagarach on June 10, 2002 7:41:20 AM]

Share this post


Link to post
Share on other sites
Of course, but for the first time this test-engine is just for my purpose and I will hold my own conventions

But of course you''re right!

I think *.jpg is the standard extension for jpegs. I''m not sure but I think there is an API to get the extension... I will check that later on.

Share this post


Link to post
Share on other sites