C++ によるファイル操作:ストリームクラスを活用した入出力処理

C++ では、ストリームクラスを介してファイルの作成、読み取り、書き込みを実現できます。この手法により、データをハードディスクやSSDなどの永続ストレージに保存し、プログラム終了後でもアクセスが可能です。

ファイル処理の基本手順は以下の3ステップです:

  • ファイルのオープン
  • データの入出力処理
  • ファイルのクローズ

ファイルオープンの方法

ファイル操作の前には、ストリームクラスを使用してファイルを開く必要があります。C++ では fstream クラスが主に使用され、以下のモードを指定してファイルを操作します。

モード 説明
ios::in ファイルを読み取り専用で開く(存在しない場合は例外)
ios::out ファイルを書き込み専用で開く(存在しない場合は新規作成)
ios::binary テキストモードではなくバイナリモードで操作
ios::app 書き込みはファイル末尾に追加
ios::trunc 既存データを削除して新規作成

複数モードの組み合わせ例:

std::fstream file_stream("data.bin", std::ios::in | std::ios::binary);

専用ストリームクラス

fstream 以外にも以下の専用クラスが用意されています:

  • ifstream: 読み取り専用ストリーム(ios::in モード)
  • ofstream: 書き込み専用ストリーム(ios::out モード)
// 読み取り用ストリーム
std::ifstream input_stream("input.txt");

// 書き込み用ストリーム
std::ofstream output_stream("output.txt");

テキストファイルへの書き込み

ofstream を使用した書き込み例:

#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ofstream writer("log.txt");
    writer << "File operation sample data";
    return 0;
}

テキストファイルからの読み取り

ifstreamgetline を使用した読み込み例:

#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ifstream reader("log.txt");
    std::string content;
    std::getline(reader, content);
    std::cout << "Read data: " << content;
    return 0;
}

バイナリファイル処理

バイナリデータの扱いには ios::binary モードを指定します。

バイナリファイルへの書き込み

#include <fstream>
#include <string>
using namespace std;

int main() {
    std::string data = "Binary data test";
    std::ofstream bin_writer("binary_data.bin", std::ios::binary);
    
    size_t data_size = data.size();
    bin_writer.write(reinterpret_cast<const char*>(&data_size), sizeof(data_size));
    bin_writer.write(data.c_str(), data_size);
    return 0;
}

バイナリファイルからの読み込み

#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ifstream bin_reader("binary_data.bin", std::ios::binary);
    size_t data_size;
    bin_reader.read(reinterpret_cast<char*>(&data_size), sizeof(data_size));
    
    char* buffer = new char[data_size + 1];
    bin_reader.read(buffer, data_size);
    buffer[data_size] = '\0';
    
    std::string loaded_data(buffer);
    delete[] buffer;
    return 0;
}

タグ: C++ file-streams binary-io

6月22日 22:43 投稿