writeメソッドの使用方法は?
write 関数は、C++ 標準ライブラリで、ファイルを上書きしたり標準出力デバイスに出力する際に利用できる関数。使用方法は以下のようになる:
#include <iostream>
#include <fstream>
int main() {
// 打开文件
std::ofstream file("example.txt");
if (file.is_open()) {
// 写入数据
file.write("Hello, World!", 13);
// 关闭文件
file.close();
} else {
std::cout << "无法打开文件!" << std::endl;
}
return 0;
}
最初に ofstream クラスを使って、ファイル “example.txt” を開いて、出力ファイルストリームオブジェクト file を作成します。次に、write 関数を使用して、文字列 “Hello, World!” をファイルに書き込みます。2 番目のパラメーター 13 は、書き込む文字数です。最後に、close 関数を使用して、ファイルを閉じます。
ファイル以外にも、標準出力デバイス(コンソールなど)にデータを出力することもできます。例:
#include <iostream>
int main() {
std::cout.write("Hello, World!", 13);
return 0;
}
上記のコードでは、write 関数で文字列「Hello, World!」を標準出力へ出力する。