2

是否可以提供一个根文件夹,然后只提供 std::ifstream 和 std::ofstream 的相对路径?

例如:

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

3 回答 3

2

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

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成员中,而不是对其进行硬编码,并且这种方法可能是获取静态修饰符(真正的帮助程序/实用程序方法)的良好候选者。

于 2013-04-28T17:23:55.157 回答
2

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

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.
于 2013-04-28T17:24:10.917 回答
2

当然,使用 Boost.Filesystem

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

文件系统或类似的东西,计划包含在标准库中。VS2012 包含了它的初步实现。因此,如果您没有 Boost,并且不想安装它,则可以使用它。

#include <filesystem>
...
namespace fs = std::tr2::sys;
fs::current_path(fs::path("C:/"));
于 2013-04-28T17:35:51.373 回答