views:

187

answers:

3

I'm reading path names from a database which are stored as relative paths in Windows format, and try to create a boost::filesystem::path from them on a Unix system. What happens is that the constructor call interprets the whole string as the filename. I need the path to be converted to a correct Posix path as it will be used locally.

I didn't find any conversion functions in the boost::filesystem reference, nor through google. Am I just blind, is there an obvious solution? If not, how would you do this?

Example:

std::string win_path("foo\\bar\\asdf.xml");
std::string posix_path("foo/bar/asdf.xml");

// loops just once, as part is the whole win_path interpreted as a filename
boost::filesystem::path boost_path(win_path);
BOOST_FOREACH(boost::filesystem::path part, boost_path) {
    std::cout << part << std::endl;
}

// prints each path component separately
boost::filesystem::path boost_path_posix(posix_path);
BOOST_FOREACH(boost::filesystem::path part, boost_path_posix) {
    std::cout << part << std::endl;
}

Edit: of course I can just replace the backslashes, but is there a solution that "just works(tm)" for both Windows and Unix plattforms?

+2  A: 

How about replacing the backslashes with slashes?

Amnon
The obvious answer :) Is there some way this could go wrong because of some suspicious escaping inside the path string? And I hoped for some boost::filesystem solution which would do just the right thing for Windows and Linux without further work on my side (*lazy*).
VolkA
Not all file systems support the same filenames, so maybe there could be problems in corner cases (or malicious users). You can review the database to see if there are any problems.
Amnon
+3  A: 

Unfortunately the Windows path grammar is conditionally compiled, and only included when compiling on Windows. I don't understand why they have done this. Anyway, this means you have at most two parsers available at all times; the portable one, which is the same as the Posix one, and the native one, which depends on which platform you currently are compiling for.

What could "just work" was to have all paths stored in the portable (Posix) format. You could parse this equally simply on all platforms.

Magnus Hoff
Sadly, I may not change the format in the Database, so I'll have to go with replacing backslashes ...
VolkA
+1  A: 

Looking at the header file, I see that if you define BOOST_WINDOWS_PATH (before including the header file) it compiles in the Windows path algorithm. I don't know if it works outside of Windows.

Amnon