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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string manipulation

Status
Not open for further replies.

cmsamcfe

Programmer
Dec 18, 2002
31
0
0
GB
i have a set of strings

"C:\test\abc\file1.dat"
"C:\test\test2\test3\file1.dat"

and I need to turn it into a filename -

"test_abc.dat"
"test_test2_test3.dat"

I have written code to produce the output required, but it doesn't remove the filename from the end of the original string.


char* tempString = temp_filename.c_str();

for (int x = 3; x < strlen(tempString); x++)
{
if(tempString[x] == '\\')
FileName += &quot;_&quot;;
else
FileName += tempString[x];
}

How can I adapt this code so that it ignores the filename and adds only the folder names to the new filename?

Thanks


 
I'm a bit unsure here. I think i know what You want but what format is variable 'FileName'? AnsiString? char[]?
Is it cleared??? With the example code You're only adding to it, not starting from scratch.

And then You're declaring:
char * tempString = temp_filename.c_str();
In my point of view it's a big no-no.

I would choose to copy it to a new stringbuffer:
char tempString[MAX_PATH]; // Could be declared with new...
strcpy(&tempString,temp_filename.c_str()); // Copy the whole string

Now they're NOT at the same adress, it's only pure text in tempString and You can do nothing wrong with that.

This should work with the code You supplied but as the goal seems a little uncertain to me i will not promise anything.

Totte
 
Unless you really want to roll your own routine, look at ExtractFileName. It takes an AnsiString and returns an AnsiString.
Code:
AnsiString FullPath = &quot;C:\\System32\\MyProg.exe&quot;;
AnsiString ProgName = ExtractFileName(FullPath);

James P. Cottingham

When a man sits with a pretty girl for an hour, it seems like a minute. But let him sit on a hot stove for a minute and it's longer than any hour. That's relativity.
[tab][tab]Albert Einstein explaining his Theory of Relativity to a group of journalists.
 
char str[MAX_PATH];
char *ptr;

strcpy(str, temp_filename.c_str());
ptr = strrchr(str, '\\');
*++ptr = '\0';

You no longer have the file name, but do have the final '\'
 
And to remove the final '\' the last line should read:
*ptr = '\0';

Totte
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top