0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++のファイル操作

Last updated at Posted at 2025-10-06

ファイル操作の練習もかねて、テキストファイルからJSON形式にするC++スクリプトを作成した。
そこで使用したfilesystem,fstreamライブラリについてまとめる。


目次

  1. 現在のパスを取得
  2. ファイルの存在確認
  3. ディレクトリの作成
  4. ディレクトリ内のファイルを取得
  5. ファイル名の取得
  6. 既存の内容を削除
  7. ファイルの読み込み
  8. ファイルへの追記
  9. ファイルの削除
  10. ファイルの更新日時取得

現在のパスを取得

std::filesystem::path current_dir = std::filesystem::current_path();

ファイルの存在確認

if (std::filesystem::exists(FILE_PATH))

ディレクトリの作成

std::filesystem::create_directories("./directory/");

ディレクトリ内のファイルを取得

for (const auto &file : std::filesystem::directory_iterator(DIR_PATH))

filestd::filesystem::directory_entry

ファイル名の取得

file.path().string()
file.path().stem().string()//拡張子なし

既存の内容を削除

std::ofstream File(FILE_PATH, std::ios::trunc);//std::ios::truncで上書きモード

ファイルの読み込み

std::ifstream ifs(FILE_PATH);
std::string line;
while (std::getline(ifs, line))//1行ずつ取得

ファイルへの追記

std::ofstream ofs(FILE_PATH, std::ios::app);//std::ios::appで追記モード
ofs << "New Line" << std::endl;

ファイルの削除

std::filesystem::remove(FILE_PATH);

ファイルの更新日時取得

auto ftime = std::filesystem::last_write_time(FILE_PATH);
auto sctp = decltype(ftime)::clock::to_sys(ftime);
std::time_t cftime = std::chrono::system_clock::to_time_t(sctp);

終わりに

例外処理をしっかりしたい

~Thank you for leading~

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?