C++でその他ファイルの実行と変更を行うには

C++では、ファイル入出力ストリーム操作を使用して、外部ファイルを操作できます。

  1. ヘッダファイル包含: #include
  2. ファイル入出力ストリームオブジェクトの作成:
std::ifstream infile; // 用于读取文件
std::ofstream outfile; // 用于写入文件
  1. ファイルをオープンします
infile.open("input.txt"); // 打开要读取的文件
outfile.open("output.txt"); // 打开要写入的文件
  1. ファイル内容の読み書き
std::string line;
while (std::getline(infile, line)) {
    // 对line进行修改
    // 将修改后的内容写入输出文件
    outfile << line << std::endl;
}
  1. ファイルを閉じる:
infile.close(); // 关闭输入文件
outfile.close(); // 关闭输出文件

input.txtは読み取りファイル、output.txtは書き込みファイルです。getline関数で一行ずつ読み込み、編集します。その後、<<演算子で書き込みファイルに出力します。

ファイル操作時には、ファイルの存在確認や読み書き権限の確認を行うように注意してください。

bannerAds