【C++】ofstreamでファイルの書き込みする

fstreamを使ってファイルにデータを書き込みします。

ofstreamでファイル書き込み

[test.txt]ファイルを開いてデータを書き込む処理です。ファイルが開けない場合はエラーとします。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
  std::ofstream ofs("test.txt");
  if (!ofs) {
    std::cout << "ファイルが開けませんでした" << std::endl;
    return -1;
  }

  ofs << "テスト書き込みです。てすとてすとてすと" << std::endl;

  return 0;
}

ofstreamでファイル書き込み(ちょっと実践編)

ちょっと実践編で、ファイルを開く部分と書き込む部分を別の関数にして、ループしながら現在時刻と適当な値を書き込んでいきます。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <chrono>
#include <format>
#include <thread>
#include <iomanip>

/**
 * @brief ログ書き込み処理
*/
bool logwrite(std::ostream& os, std::string& msg)
{
  // 時刻の整形
  auto now = std::chrono::system_clock::now();
  auto time = std::chrono::system_clock::to_time_t(now);
  std::tm* lt = std::localtime(&time);
  uint64_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
  std::stringstream ss;
  ss << lt->tm_year+1900;
  ss << "/" << std::setfill('0') << std::right << std::setw(2) << lt->tm_mon+1;
  ss << "/" << std::setfill('0') << std::right << std::setw(2) << lt->tm_mday;
  ss << " " << std::setfill('0') << std::right << std::setw(2) << lt->tm_hour;
  ss << ":" << std::setfill('0') << std::right << std::setw(2) << lt->tm_min;
  ss << ":" << std::setfill('0') << std::right << std::setw(2) << lt->tm_sec;
  ss << "." << std::setfill('0') << std::right << std::setw(3) << (ms % 1000);

  // データの書き込み
  os << ss.str();
  os << "," << msg;
  os << std::endl;

  return true;
}

int main()
{
  std::ofstream ofs("test.txt");
  if (!ofs) {
    std::cout << "ファイルが開けませんでした" << std::endl;
    return -1;
  }

  int n = 0;
  while (n < 5) {
    // 書き込みデータ作成
    std::string str;
    str = "テスト書き込み…" + std::to_string(n) + "回目の書き込みです。";

    // 書き込み処理呼び出し
    bool ok = logwrite(ofs, str);

    ++n;
    std::this_thread::sleep_for(std::chrono::milliseconds(10));   // 10ms Wait
  }

  return 0;
}

【test.txt】
2024/02/17 21:26:51.095,テスト書き込み…0回目の書き込みです。
2024/02/17 21:26:51.108,テスト書き込み…1回目の書き込みです。
2024/02/17 21:26:51.121,テスト書き込み…2回目の書き込みです。
2024/02/17 21:26:51.133,テスト書き込み…3回目の書き込みです。
2024/02/17 21:26:51.145,テスト書き込み…4回目の書き込みです。

logwrite関数でファイルへの出力データの整形及び出力を行っています。

15行目から27行目までが現在の時刻を年月日時分秒ミリ秒の形に整形しています。
29秒目から32行目までが日時+出力データを書き込んでいます。

39行目がファイルを書き込みモードで開く処理です。
元々同名のファイルが存在する場合は、ファイル内のデータは削除された状態で開かれます。
(ファイルオープンモード参照)

46行目から56行目のループ内で、logwrite関数の呼び出しと10msのWaitを行っています。

ファイルオープンモードについて

ofstreamでファイルを開くとき、ファイルのオープンモードを指定することにより上書きや追記等を選択することができます。

std::ios::out書き込みモード(デフォルト)
書き込み時、元の内容は破棄されます
std::ios::in読み取りモード
std::ios::app追記モード
常にファイルの末尾に書き込み
std::ios::ate開いた時にファイル末尾に移動します
書き込み位置は移動することが可能です
std::ios::trunc開いた時にファイルの内容を破棄します。
std::ios::binaryバイナリモードです

ファイルを追記モードで開いて書き込みする場合は、以下の様なコードになります。

  std::ofstream ofs("test.txt", std::ios::app);

ofstreamは出力ストリームなので「std::ios::out」がデフォルトになっているので、「std::ios::out | std::ios::app」の様に記載しなくても問題ありません。

スポンサーリンク

  • この記事を書いた人

まさじぃ

ダメプログラマ歴17年です。 プログラミング関連の事や、 自分で使って良かったもの等の紹介をメインにやっています。

-プログラミング
-