c++ - Splitting an absolute file path
<p>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</p>

<pre><code>     /home/dir1/dir2/dir3/dir4/file
</code></pre>

<p>I would like to do</p>

<pre><code>     int ret = chdir("home/dir1/dir2/dir3/dir4");
</code></pre>

<p>My question is how can I split the user-given string into</p>

<pre><code>     /home/dir1/dir2/dir3/dir4/
</code></pre>

<p>and</p>

<pre><code>     file
</code></pre>

<p><strong>EDIT</strong>I 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</p>