简体   繁体   English

std文件流的相对路径

[英]Relative path for std file streams

Is it possible to provide a root folder and after this only relative paths for std::ifstream and std::ofstream? 是否可以提供一个根文件夹,并且在此之后仅提供std :: ifstream和std :: ofstream的相对路径?

For example: 例如:

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

You can define your own method which knows the working directory and prepends the correct string to the filename. 您可以定义自己的方法,该方法知道工作目录并将正确的字符串添加到文件名中。

std::string prependFilePath(const std::string &filename);

Then construct a stream with 然后用

stream(prependFilePath("isample.txt").c_str());

Example: 例:

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

In a real implementation, you should store the path (eg: ../ ) in a const std::string member rather than hard-coding it and probably this method is a good candidate for getting a static modifier (real helper/utility method). 在实际的实现中,您应该将路径(例如: ../ )存储在const std::string成员中,而不是对其进行硬编码,并且该方法可能是获取静态修饰符的不错选择(实际的辅助方法/实用方法) )。

If you write a function, yes. 如果编写函数,则可以。
The fstream -objects do not impose anything on you, you can specify a relative path or an absolute path. fstream -object不会对您施加任何影响,您可以指定相对路径或绝对路径。

Cplusplus.com states: 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.

Sure, using Boost.Filesystem 当然可以,使用Boost.Filesystem

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

Filesystem, or something like it, is slated for inclusion in the standard library. 文件系统或类似的文件计划包含在标准库中。 VS2012 includes a preliminary implementation of it. VS2012包括它的初步实现。 So if you don't have Boost, and you don't feel like installing it, you can use that. 因此,如果您没有Boost,并且不想安装它,则可以使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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