2013-04-28 75 views
2

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

例如:

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

回答

2

如果你写一个函数,是的。
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. 
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构件而不是硬编码它,可能这种方法是获得静态mod的好选择ifier(真正的帮手/实用方法)。

2

当然,使用Boost.Filesystem的

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

文件系统,或类似的东西,被提名为列入标准库。 VS2012包括其初步实施。所以如果你没有升级,而你又不想安装它,那么你可以使用它。

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

感谢您添加关于'tr2'实现的信息。 – 2013-04-28 17:43:49