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

関数を書く場合は、はい。-objects はユーザーに何も課しません。相対パスまたは絶対パスを指定できます
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.
于 2013-04-28T17:24:10.917 に答える
2

もちろん、Boost.Filesystem を使って

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

ファイルシステム、またはそれに類するものは、標準ライブラリに含まれる予定です。VS2012 には、その暫定的な実装が含まれています。したがって、Boost がなく、インストールしたくない場合は、Boost を使用できます。

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