Simple string operations?

Started by
6 comments, last by DarkKiller 21 years, 10 months ago
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++?
DarkMcNugget next time... ;)
Advertisement
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.

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);
}
DarkMcNugget next time... ;)
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]
--------<a href="http://www.icarusindie.com/rpc>Reverse Pop Culture
I worked with VB for 4 years

I used the strncmp() function some time ago and I searched for it the last hour because I thought its name is cmpstr() ....

thankx a lott!
DarkMcNugget next time... ;)
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(...);        ...} 

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]
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.
DarkMcNugget next time... ;)

This topic is closed to new replies.

Advertisement