2
1

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.

外部ファイル(ifstream)の内容を内部メモリ(vector)へ読み込む方法

Last updated at Posted at 2021-08-14

実装例

# include <fstream>
# include <iostream>
# include <vector>

void main(){
std::ifstream inputFile("ファイルパス");
std::vector<char> data{std::istreambuf_iterator<char>(inputFile), std::istreambuf_iterator<char>()};
std::cout << data[0] << std::endl;
}

解説

ifstreamはファイル読み込みに使用するクラスです。
fstreamがファイル入出力で、読み込み専用なのでinputのiがついてifstreamとなります。
出力用だとoutputのoがついてofstreamです。

vectorの波カッコは一様初期化というコンストラクタの呼び出し方です。
vectorコンストラクタに
vector(InputIter first, InputIter last, const Allocator& a = Allocator());
というものがあります。
第一引数のイテレータから第二引数のイテレータまでの範囲をvectorのメモリに格納してくれるというものです。
ifstreamのイテレータを作成するためistreambuf_iteratorを使用します。
istreambuf_iteratorは引数を指定しなければendイテレータと等しくなるため、第二引数に使用できます。

注意点

vectorのコンストラクタを丸カッコで呼び出すこともできます。
std::vector<char> data((std::istreambuf_iterator<char>(inputFile)), (std::istreambuf_iterator<char>()));
この時、vectorコンストラクタの第一引数、第二引数共にカッコでくくられていることに注意してください。
例えばカッコを削除してしまい、
std::vector<char> data((std::istreambuf_iterator<char>(inputFile)), (std::istreambuf_iterator<char>()));
とするところを
std::vector<char> data(std::istreambuf_iterator<char>(inputFile), std::istreambuf_iterator<char>());
としてしまうと思った通りの挙動にならないので注意してください。
data[0]などとアクセスするタイミングでビルドエラーになります。

理由は、カッコを無くした場合関数宣言になってしまうからです。
std::vector<char>が戻り値でstd::istreambuf_iterator<char>(inputFile)std::istreambuf_iterator<char>()が引数のdataという関数が宣言されてしまいます。
そのため、data[0]などと記述すると怒られます。

2
1
2

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?