C++のテキストファイルの読み書き方法は?
C++では、fstreamクラスが標準ライブラリに含まれ、テキストファイルの読み込みと書き込みに使用できます。fstreamクラスは、ファイル入出力操作に関連するメンバ関数と演算子オーバーロードを提供します。
以下にいくつかのテキストファイルの読み書き操作方法を示します。
- ファイルを開く: ファイルは`fstream`クラスの`open`関数を使用して開くことができます.`open`関数は2つの引数を取ります: ファイル名とオープニングモード(入力、出力、または入出力)です。
#include <fstream>
using namespace std;
int main() {
ofstream file;
file.open("example.txt"); // 打开文件example.txt
// 或者
// ofstream file("example.txt");
// 写入操作...
file.close(); // 关闭文件
return 0;
}
- ファイルに出力:
ofstreamクラスオブジェクトの<< 演算子を使用すると、データをファイルに出力できます。使い方としては、coutオブジェクトと同じです。
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!" << endl;
file << "This is a text file." << endl;
file.close();
}
return 0;
}
- ファイルの読み込みでは、>>演算子を使用してifstreamクラスオブジェクトからデータを読み取ります。ifstreamオブジェクトはcinオブジェクトと同じように使用できます。
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
if (file.is_open()) {
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
return 0;
}
これらはテキストファイルの読み込みと書き込みの基本的な方法の一部であり、必要に応じてfstreamクラスで提供されている他のメンバー関数と演算子オーバーロードをさらに探索できます。