// 示例代码:读写文件的简单示例
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 写入文件
string filename = "example.txt";
ofstream outFile(filename);
if (outFile.is_open()) {
outFile << "Hello, C++ File!" << endl;
outFile.close();
cout << "文件写入成功!" << endl;
} else {
cout << "无法打开文件进行写入。" << endl;
return 1;
}
// 读取文件
ifstream inFile(filename);
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << "从文件读取的内容: " << line << endl;
}
inFile.close();
} else {
cout << "无法打开文件进行读取。" << endl;
return 1;
}
return 0;
}
#include <fstream> 用于文件操作,#include <string> 用于处理字符串。ofstream 对象 outFile 打开文件并写入内容。如果文件成功打开,则写入一行文本并关闭文件。ifstream 对象 inFile 打开文件并逐行读取内容。如果文件成功打开,则输出每一行内容到控制台并关闭文件。这个示例展示了如何使用 C++ 进行基本的文件读写操作。
上一篇:c++函数的声明与定义
下一篇:c++创建线程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站