Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ get directory prefix

For example I have the string "root/data/home/file1.txt" I would like to get "root/data/home" Is there a convenient function in C++ that allows me to do this or should I code it myself?

like image 351
Mark Avatar asked Jun 12 '11 01:06

Mark


2 Answers

You can do basic string manipulation, i.e.

std::string path = "root/data/home/file1.txt";
// no error checking here
std::string prefix = path.substr(0, path.find_last_of('/'));

or take a third option like Boost.Filesystem:

namespace fs = boost::filesystem;
fs::path path = "root/data/home/file1.txt";
fs::path prefix = path.parent_path();
like image 83
Luc Danton Avatar answered Oct 14 '22 09:10

Luc Danton


If you're on a POSIX system, try dirname(3).

like image 44
John Zwinck Avatar answered Oct 14 '22 11:10

John Zwinck