std文件流的相对路径

Relative path for std file streams

本文关键字:相对 路径 文件 std      更新时间:2023-10-16

是否有可能为std::ifstream和std::ofstream提供一个根文件夹,在此之后只有相对路径?

例如:

SetFileStreamRootFolder("C:/");
std::ifstream stream("isample.txt"); //C:isample.txt file
std::ofstream stream("osample.txt"); //C:osample.txt file

如果你写一个函数,可以。
fstream -对象不会强加给您任何东西,您可以指定一个相对路径或绝对路径。

Cplusplus.com状态:

Parameters:
filename
String with the name of the file to open.
Specifics about its format and validity 
depend on the library implementation and running environment.

您可以定义自己的方法,该方法知道工作目录并在文件名前添加正确的字符串。

std::string prependFilePath(const std::string &filename);
然后用 构造一个流
stream(prependFilePath("isample.txt").c_str());

的例子:

std::string prependFilePath(const std::string &filename)
{
    // The path can be relative or absolute
    return "../" + filename;
}

在实际实现中,您应该将路径(例如:../)存储在const std::string成员中,而不是硬编码它,并且可能这种方法是获得静态修饰符(真正的助手/实用程序方法)的良好候选。

当然,使用Boost。文件系统

#include <boost/filesystem.hpp>
...
namespace fs = boost::filesystem;
fs::current_path("C:/");

Filesystem,或类似的东西,预定包含在标准库中。VS2012包含了它的初步实现。所以如果你没有Boost,并且你不想安装它,你可以使用它。

#include <filesystem>
...
namespace fs = std::tr2::sys;
fs::current_path(fs::path("C:/"));