Mark
Mark

Reputation: 8688

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?

Upvotes: 9

Views: 7069

Answers (4)

Ben Voigt
Ben Voigt

Reputation: 283911

This is rather platform-dependent. For example, Windows uses '\' for a path separator (mostly), Unix uses '/', and MacOS (prior to OSX) uses ':'.

The Windows-specific API is PathRemoveFileSpec.

Upvotes: 0

Luc Danton
Luc Danton

Reputation: 35469

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();

Upvotes: 18

Charlie Martin
Charlie Martin

Reputation: 112424

There's certainly no convenient function in the language itself. The string library provides find_last_of, which should do well.

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249642

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

Upvotes: 3

Related Questions