您的位置:首页 >C++如何写入文件数据详解
发布于2025-09-21 阅读(0)
扫一扫,手机访问
首先包含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 << "Hello, this is a line of text.\n";
file << "Another line here.\n";
file.close();
} else {
cout << "无法打开文件!" << endl;
}
示例:
ofstream file("example.txt", ios::app);
if (file.is_open()) {
file << "This line is appended.\n";
file.close();
}
int age = 25;
double price = 19.99;
string name = "Alice";
ofstream out("data.txt");
if (out.is_open()) {
out << "Name: " << name << endl;
out << "Age: " << age << endl;
out << "Price: $" << price << endl;
out.close();
}
基本上就这些。只要记得检查文件是否成功打开,并在操作完成后调用 close(),就能安全地写入数据。
下一篇:Win10进入高级选项的多种方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9