-
Trouble with strings
Below there's a function that given a string of the form "../data/afile.txt" separates the path("../data/") from the file name("afile.txt"). I can get the path succesfully, but unfortunately I can't get the file name correctly.
Code:
void SplitStringToFileAndPath(char **file, char **path, const char *string)
{
int len = strlen(string);
int index = 0, j = 0;
// search the string from the end to beggining to find the last '/' or '\' character
for(int i = len; string[i] != '/' && string[i] != '\\'; i--)
j++;
// find the position from the beginning of the last '/' or '\'
index = len - j + 1;
// extract path
//delete *path;
*path = new char[index + 1];
// copy path
for(int i = 0; i < index; i++)
(*path)[i] = string[i];
(*path)[index] = '\0';
// extract filename
//delete *file;
*file = new char[len - index + 1];
for(int i = 0; i < (len - index); i++)
(*file)[i] = string[(len - index) + i];
(*file)[len - index] = '\0';
}
-
Do you have a particular reason for mucking about with allocating char arrays, as opposed to say passing a reference to a std::string to store your results?
You should simplify the maths
One copy is
for ( i = 0, j = 0; j < index ; i++, j++ )
The other is
for ( i = 0, j = index+1 ; j < len ; i++, j++ )
-
Why something so big complicated and replying on C strings and pointers? Here is simply how I would would do it:
Code:
#ifndef GET_PATH_20100802_1812
#define GET_PATH_20100802_1812
#include <string>
namespace Stuff
{
namespace File
{
std::wstring GetFile(const std::wstring& strFullPath)
{
auto pos = strFullPath.rfind(L'\\');
if (pos == std::wstring::npos)
return L"";
return strFullPath.substr(pos + 1);
}
std::wstring GetPath(const std::wstring& strFullPath)
{
auto pos = strFullPath.rfind(L'\\');
if (pos == std::wstring::npos)
return L"";
return strFullPath.substr(0, pos);
}
}
}
#endif
Combine those two and you have what you want.
-
Thanks for help, I corrected the function.
I use C strings just for training.