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

  • std::ios::in
    • ファイルを開いて読み取ります。
  • std::ios::out
    • ファイルを開いて書き込みます。
  • std::ios::ate
    • 開始位置はファイルの末尾です。
  • std::ios::app
    • ファイルに追加します。すなわち、常にファイルの末尾に書き込みます。
  • std::ios::trunc
    • ファイルを切り捨てます。すなわち、内容を削除します。
  • std::ios::binary
    • バイナリモード

ファイルオープン例

実行ファイルと同じ階層にある“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] 佐藤 陽悦
    同じく
  • game-engineer/classes/2022/game-programing-2/first-term/9/9-02-1.txt
  • 最終更新: 3年前
  • by root