简体   繁体   中英

boost::filesystem - how to create a boost path from a windows path string on posix platforms?

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?

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.

用斜杠替换反斜杠怎么样?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM