Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

r->filename value changed?

Status
Not open for further replies.

GoSooJJ

Programmer
Feb 24, 2001
76
US
Hi there,
Since I do not good understanding of pointers, I can not figure out why I'm missing from below code. Basically, I want to get filename from the url and if filename(media_id)is correct then return OK. But the problem is r->filename is changed. from /data/htdocs/localhost/12345_full.wmv to /data/htdocs/localhost/12345

Can anyone help me how I can fix this problem?

filename = strrchr(r->filename, (int) '/');
filename++;
media_id = atoi(strtok(filename, "_"));
 
You are setting filename (which I'm guessing is a char* pointer) to the pointer returned from strrchr(), which is the last '/' in the string. So filename is now "/12345_full.wmv".

The next line increments the pointer by one char. Now filename is "12345_full.wmv".

The strtok() function modifies the first parameter (i.e. filename) by changing the '_' to a NULL. So now filename is "12345".

The thing you need to remember is that filename and r->filename are both pointing to the same memory, so when strtok() changes filename, r->filename is also changed.

If that isn't what you want, you should create a new char* string (using the 'new' keyword) that is the size of the string returned from strrchr() (plus 1 for the terminating NULL). Then copy filename into the new string and pass that string to strtok(). Don't forget to delete the new string when you're done with it (with the 'delete []' keyword).
 
Thanks for the great answer cpjust. However, can you show me the example of what you just described? I just can not make sure that I'm doing right (I'm guessing too many times). Please help me one more time if you can :)
TIA
 
Code:
char* pTemp = strrchr( r->filename, (int) '/' );
++pTemp;
char* filename = new char[ strlen( pTemp ) + 1 ];
strcpy( filename, pTemp );
media_id = atoi( strtok( filename, "_" ) );
...
delete [] filename;  // Delete filename when you don't need it any more.
filename = NULL;
 
> media_id = atoi(strtok(filename, "_"));
You should really check the return result of strtok() first, because if there is no underscore in your filename, strtok will return NULL.


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top