LoginSignup
25
13

More than 3 years have passed since last update.

C++でCSVファイルを読み書きする方法

Last updated at Posted at 2020-04-25

はじめに

 C++でcsvファイルの読み込み・書き込み方法を調べてみたので、
 本記事にまとめる。

環境

  • 動作環境
    Visual Studio 2019
  • 言語
    C++

インクルードするヘッダーファイル

csvファイルを扱うために使用するヘッダーファイルは以下である。

  • string
  • fstream
  • sstream

CSVファイル読み込み・書き込み方法

ReadWriteCsv.cpp
#include <string>
#include <fstream>
#include <sstream>

int main () {
  std::string str_buf;
  std::string str_conma_buf;
  std::string input_csv_file_path  = "読み込むcsvファイルへのパス";
  std::string output_csv_file_path = "書き込むcsvファイルへのパス";

  // 読み込むcsvファイルを開く(std::ifstreamのコンストラクタで開く)
  std::ifstream ifs_csv_file(input_csv_file_path  );

  // 書き込むcsvファイルを開く(std::ofstreamのコンストラクタで開く)
  std::ofstream ofs_csv_file(output_csv_file_path );

  // getline関数で1行ずつ読み込む(読み込んだ内容はstr_bufに格納)
  while (getline(ifs, str_buf)) {    
    // 「,」区切りごとにデータを読み込むためにistringstream型にする
    std::istringstream i_stream(str_buf);

    // 「,」区切りごとにデータを読み込む
    while (getline(i_stream, str_conma_buf, ',')) {
       // csvファイルに書き込む
       ofs_csv_file << str_conma_buf << ',';
    }
    // 改行する
    ofs_csv_file << std::endl;
  }

  // クローズ処理は不要[理由]ifstream型・ofstream型ともにデストラクタにてファイルクローズしてくれるため
}

参考

ifstreamクラスの仕様
ofstreamクラスの仕様
getlineの関数仕様

気づいたこと

  • 1つのcsvファイルに対して読み込み・書き込むを同時にすることはできないっぽい
    もし知っていたら展開してもらえると嬉しいです。

  • ifstream・ofstream型はコンストラクタでファイルオープンしてくれるが、オープンするメソッドもある。
    例えば、オープンは別の関数でさせたい場合やインスタンスをメンバ変数にしたいときはオープンメソッドを使う。

25
13
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
25
13