C++でファイルを作成、書き込み、読み込みする方法は?
C++でファイルを作成、書き込み、読み込みする方法はいくつかあります。以下にいくつかの方法を示します。
方法1:fstreamを使用する
fstream
は、ファイルの入出力を扱うためのC++の標準ライブラリです。以下は、fstream
を使用してファイルを作成、書き込み、読み込む方法の例です。
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// ファイルを作成して書き込む
ofstream outfile("example.txt");
outfile << "Hello, world!" << endl;
outfile.close();
// ファイルを読み込む
ifstream infile("example.txt");
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
return 0;
}
方法2:Cのファイル操作関数を使用する
C++はC言語と互換性があるため、Cのファイル操作関数を使用してファイルを作成、書き込み、読み込むこともできます。以下は、fopen
、fprintf
、fscanf
、fclose
を使用してファイルを作成、書き込み、読み込む方法の例です。
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
// ファイルを作成して書き込む
FILE* outfile = fopen("example.txt", "w");
fprintf(outfile, "Hello, world!\n");
fclose(outfile);
// ファイルを読み込む
FILE* infile = fopen("example.txt", "r");
char line[100];
while (fgets(line, sizeof(line), infile)) {
cout << line;
}
fclose(infile);
return 0;
}