c++ - Splitting an absolute file path

The_Questioner picture The_Questioner · Feb 20, 2016 · Viewed 14k times · Source

I'm writing a C++ program for a school assignment. At some point, the question requires me to change directories, which I know how to do. However, the user will provide the program with the absolute path of a file. What I'm trying to do is to change the directory to where that file is. For example, if I'm in a directory dir2, and the user want to go to the file

     /home/dir1/dir2/dir3/dir4/file

I would like to do

     int ret = chdir("home/dir1/dir2/dir3/dir4");

My question is how can I split the user-given string into

     /home/dir1/dir2/dir3/dir4/

and

     file

EDITI figured it out. I first converted the absolute pathname from a const char* to a string. Then I used the .find_last_of("/") string member to find the position of the last "/" in the string. Then I used the .substr() member to get the substring from 0 to that position returned by .find_last_of

Answer

Berni picture Berni · Feb 20, 2016

Simply get the last index of the "/" character in the file path, and snip the file with it's extension from the string.

1) Check that the directory listing has a "/". If not - throw an error.

2) Get the last index of the "/" in the string.

3) Return a sub string of the directory string, using the last index of function result (a number) as your starting index and the total length of the directory string.

Hope that helps.