首先包含fstream头文件,然后使用ofstream类创建输出流对象并指定文件名,若文件不存在则自动创建,存在则默认覆盖内容,接着通过is_open()检查文件是否成功打开,最后用<<操作符写入数据并关闭文件。

在C++中向文件写入数据,主要使用标准库中的 fstream 头文件提供的工具。通过 ofstream(output file stream)类,可以轻松地将数据写入文件。
#include <fstream>
#include <iostream>
using namespace std;
示例代码:
ofstream file("example.txt");
if (file.is_open()) {
file
file
file.close();
} else {
cout
}
示例:
ofstream file("example.txt", ios::app);
if (file.is_open()) {
file
file.close();
}
int age = 25;
double price = 19.99;
string name = "Alice";
ofstream out("data.txt");
if (out.is_open()) {
out
out
out
out.close();
}
基本上就这些。只要记得检查文件是否成功打开,并在操作完成后调用 close(),就能安全地写入数据。
以上就是C++如何向文件中写入数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号