Reputation: 20780
Is it possible to provide a root folder and after this only relative paths for std::ifstream and std::ofstream?
For example:
SetFileStreamRootFolder("C:/");
std::ifstream stream("isample.txt"); //C:\isample.txt file
std::ofstream stream("osample.txt"); //C:\osample.txt file
Upvotes: 2
Views: 1401
Reputation: 103713
Sure, using 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. So if you don't have Boost, and you don't feel like installing it, you can use that.
#include <filesystem>
...
namespace fs = std::tr2::sys;
fs::current_path(fs::path("C:/"));
Upvotes: 2
Reputation: 19805
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 (e.g.: ../
) 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).
Upvotes: 2
Reputation: 13207
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.
Cplusplus.com states:
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.
Upvotes: 2