T
Tatu Portin
I need to implement simple function to get current directory from
program directory.
e.g. /home/tatu/src/main -> /home/tatu/src
where main is the currently running program.
i.e. argv[0] == /home/tatu/src/main.
First, I did it with C-style:
// start-of-file
static const char*
parse_currentdir(const char* const program_location)
{
register int i;
const char* const loc = program_location;
size_t size = strlen(loc);
for (i = (size - 1); (i >= 0) && (loc != DIR_SEPARATOR); --i)
;
if (loc == DIR_SEPARATOR)
{
char* curdir = (char*) malloc((i + 1) * sizeof(char));
if (curdir != NULL)
{
strncpy (curdir, loc, (size_t) i);
curdir = '\0';
return curdir;
}
else
{
// Memory allocation error.
}
}
else
{
// There was no DIR_SEPARATOR in LOC.
}
const char* curdir = ".";
return curdir;
}
int
main (int argc, const char* const argv[])
{
const char* curdir = parse_currentdir (argv[0]);
return 0;
}
// end-of-file
But then I don't learn anything about C++. In particular, I found
out[1] that I could use find_last_of() member routine of C++ string
class. But find_last_of() returns type of size_type, and I cannot
figure out how I should use the size_type to create smaller string
containing only current path.
Can I convert size_type to an iterator?
[1] found out:
http://www.cppreference.com/cppstring/end.html
If you know better reference pages, please include them in your
answer.
program directory.
e.g. /home/tatu/src/main -> /home/tatu/src
where main is the currently running program.
i.e. argv[0] == /home/tatu/src/main.
First, I did it with C-style:
// start-of-file
static const char*
parse_currentdir(const char* const program_location)
{
register int i;
const char* const loc = program_location;
size_t size = strlen(loc);
for (i = (size - 1); (i >= 0) && (loc != DIR_SEPARATOR); --i)
;
if (loc == DIR_SEPARATOR)
{
char* curdir = (char*) malloc((i + 1) * sizeof(char));
if (curdir != NULL)
{
strncpy (curdir, loc, (size_t) i);
curdir = '\0';
return curdir;
}
else
{
// Memory allocation error.
}
}
else
{
// There was no DIR_SEPARATOR in LOC.
}
const char* curdir = ".";
return curdir;
}
int
main (int argc, const char* const argv[])
{
const char* curdir = parse_currentdir (argv[0]);
return 0;
}
// end-of-file
But then I don't learn anything about C++. In particular, I found
out[1] that I could use find_last_of() member routine of C++ string
class. But find_last_of() returns type of size_type, and I cannot
figure out how I should use the size_type to create smaller string
containing only current path.
Can I convert size_type to an iterator?
[1] found out:
http://www.cppreference.com/cppstring/end.html
If you know better reference pages, please include them in your
answer.