#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 创建一个ofstream对象,用于写入文件
ofstream outfile;
// 打开一个名为 "example.txt" 的文件,如果文件不存在则创建它
outfile.open("example.txt");
// 检查文件是否成功打开
if (!outfile) {
cout << "无法打开文件进行写入!" << endl;
return 1;
}
// 写入一些文本到文件中
outfile << "Hello, World!" << endl;
// 关闭文件
outfile.close();
// 创建一个ifstream对象,用于读取文件
ifstream infile;
// 打开刚才创建的 "example.txt" 文件
infile.open("example.txt");
// 检查文件是否成功打开
if (!infile) {
cout << "无法打开文件进行读取!" << endl;
return 1;
}
// 创建一个字符串变量,用于存储从文件中读取的内容
string line;
// 逐行读取文件内容并输出到控制台
while (getline(infile, line)) {
cout << line << endl;
}
// 关闭文件
infile.close();
return 0;
}
#include <iostream>, #include <fstream>, #include <string> 引入了必要的库,以便我们可以使用输入输出流和字符串。ofstream outfile; 用于写入文件。outfile.open("example.txt"); 打开或创建一个名为 example.txt 的文件。outfile 是否为 false 来确保文件成功打开。outfile << "Hello, World!" << endl; 将字符串写入文件。outfile.close(); 关闭文件以确保所有数据都被正确写入。ifstream infile; 用于读取文件。infile.open("example.txt"); 打开之前创建的文件。infile 是否为 false 来确保文件成功打开。while (getline(infile, line)) 逐行读取文件内容,并将其输出到控制台。infile.close(); 关闭文件以释放资源。上一篇:c++ multimap
下一篇:c++选择排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站