0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Visual Studioでファイルの相対参照をする

Posted at

Visual Studioでファイルの相対参照をしたい

Visual Studioを使っていて、ファイルの場所を指定するのに、.exeファイルが生成されるディレクトリからの相対参照をする必要がある。
しかし、普段から使っていたら.exeがどこの階層にできるのか覚えていられるが、しばらく時間が空くと、どこにできるのか忘れてしまう。
そこで、参照するリソースのフォルダを移動させることによって、つねにカレントディレクトリからの相対参照できるようにしてみた。

やり方

以下のようなファイル攻勢になっているとする。なお、Visual Studioにおけるプロジェクト名はMyProjectとする。
また、x64 デバッグである。

source/repos/MyProjct
|-.vs/
|- Debug/
|- MyProject/ 
|- x64
|- MyProject.sln
source/repos/MyProjct/Myprojct
|- Debug
|- include
|- resources  -|  <- これを参照したい
|- main.cpp    |-test.txt
|- x64
|- MyProject.vcxproj
|- MyProject.vcxproj.filters
|- MyProject.vcxproj.user
test.txt
hello

プロジェクト->プロパティとクリックして、
構成->すべての構成
プラットフォーム->すべてのプラットフォーム
として、
ビルドイベント->ビルド後のイベント
をクリックする。

そこで、コマンドラインに以下を追加。

copy "$(SolutionDir)MyProject\resources" "$(OutDir)"  

これで、.exeファイルが出力される階層と同じ階層にresourcesフォルダがコピーされる。
あとは、読み込むだけ。

main.cpp
# include <iostream>
# include <fstream>

int main(int argc, char** argv)
{
	std::string filePath = ".\\resources\\test.txt";
	
	std::ifstream ifs;
	ifs.open(filePath, std::ios::in);
	while (!ifs.eof()) {
		std::string text_buff;
		std::getline(ifs, text_buff);
		std::cout << text_buff;
	}

	return 0;
}

出力結果

hello

まとめ

Visual Studioでビルド後に、参照したいフォルダをコピーして.exeと同じ階層に置いてやることで、いつでも相対参照でアクセスできるようになる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?