ファイル入出力(補足と復習)

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

ファイルオープン例

実行ファイルと同じ階層にある“dat.txt”を読込モードでオープンする例

  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6. std::ofstream ofs("dat.txt", std::ios::out);
  7. if (ofs.fail())
  8. {
  9. std::cout << "ファイルが開けませんでした。" << std::endl;
  10. return 0;
  11. }
  12.  
  13. ofs << "あいうえお かきくけこ" << std::endl;
  14. std::cout << "データを書き込みました。" << std::endl;
  15.  
  16. ofs.close();
  17. retrun 0;
  18. }

実行ファイルと同じ階層にある“dat.txt”を書き込みモードでオープンする例

  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6. std::ifstream ifs("dat.txt", std::ios::in);
  7. if (ifs.fail())
  8. {
  9. std::cout << "ファイルが開けませんでした。" << std::endl;
  10. return 0;
  11. }
  12. //この辺でごにょごにょ読み込みを行う
  13. //ifs.close();
  14. retrun 0;
  15. }
[09/09 9:13] 佐藤 陽悦
    https://cpprefjp.github.io/reference/sstream.html
​[09/09 9:13] 佐藤 陽悦
    sstream:文字列をストリームとして使う→文字列分割
​[09/09 9:14] 佐藤 陽悦
    https://www.delftstack.com/ja/howto/cpp/how-to-read-a-file-line-by-line-cpp/
行単位読み込み
​[09/09 9:14] 佐藤 陽悦
    同じく