使用ofstream可轻松创建并写入文件,需包含<fstream>头文件,定义std::ofstream对象并检查is_open()状态,确保文件成功打开后,用<<操作符写入内容,最后调用close()关闭文件。

在C++中使用
ofstream
<fstream>
std::ofstream
要使用
ofstream
<fstream>
<iostream>
<string>
#include <iostream> #include <fstream> #include <string>
使用
std::ofstream
open()
std::cout
<<
std::ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!" << std::endl;
file << "This is a test file." << std::endl;
file.close();
} else {
std::cerr << "无法创建或打开文件!" << std::endl;
}
写入前检查文件是否成功打开非常重要,避免因权限、路径等问题导致写入失败。
立即学习“C++免费学习笔记(深入)”;
可以使用
is_open()
true
false
下面是一个完整的例子,创建一个名为
data.txt
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream outfile("data.txt");
if (!outfile) {
std::cerr << "无法创建文件 data.txt" << std::endl;
return 1;
}
outfile << "第一行:C++ 文件操作" << std::endl;
outfile << "第二行:使用 ofstream 写入数据" << std::endl;
outfile.close();
std::cout << "数据已成功写入文件!" << std::endl;
return 0;
}
运行后会在程序所在目录生成
data.txt
基本上就这些。只要记得检查文件是否打开成功,避免静默失败,就能安全地创建和写入文件。
以上就是C++中如何使用ofstream创建一个新文件并写入数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号