C ++ファイル
C ++ファイル
ライブラリを使用すると、fstream
ファイルを操作できます。
fstream
ライブラリを使用するには、標準ファイルとヘッダーファイルの両方を<iostream>
インクルードします。<fstream>
例
#include <iostream>
#include <fstream>
fstream
ライブラリには、ファイルの作成、書き込み、または読み取りに使用される3つのクラスが含まれています。
Class | Description |
---|---|
ofstream |
Creates and writes to files |
ifstream |
Reads from files |
fstream |
A combination of ofstream and ifstream: creates, reads, and writes to files |
ファイルの作成と書き込み
ファイルを作成するには、ofstream
またはfstream
クラスのいずれかを使用して、ファイルの名前を指定します。
ファイルに書き込むには、挿入演算子(<<
)を使用します。
例
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
//
Write to the file
MyFile << "Files can be tricky, but it is fun
enough!";
//
Close the file
MyFile.close();
}
なぜファイルを閉じるのですか?
これは良い習慣と考えられており、不要なメモリスペースをクリーンアップできます。
ファイルを読む
ファイルから読み取るには、ifstream
またはfstream
クラスのいずれかとファイルの名前を使用します。
また、関数(クラスに属する)while
と一緒にループを使用して、ファイルを1行ずつ読み取り、ファイルの内容を出力することに注意してください。getline()
ifstream
例
// Create a
text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while
loop together with the getline() function to read the file line by line
while (getline (MyReadFile,
myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();