本资源提供详细的C++编程示例,展示如何实现TXT文件的基本操作,包括文件的打开、内容读取及信息写入等功能。适合初学者学习实践。
在C++中读取和写入txt文件的基本方法如下:
1. 写入数据到文本段落件:
```cpp
#include
using namespace std;
int main() {
ofstream file(example.txt); // 创建输出流对象,指定要创建或打开的文件名
if (file.is_open()) { // 检查文件是否成功打开
file << Hello, World!; // 写入数据到文件中
file.close(); // 关闭文件
}
return 0;
}
```
2. 从文本段落件读取数据:
```cpp
#include
#include
using namespace std;
int main() {
ifstream file(example.txt); // 创建输入流对象,指定要打开的文件名
if (file.is_open()) {
string line;
while(getline(file, line)) { // 逐行读取数据
cout << line << \n; // 输出每一行的数据到控制台
}
file.close(); // 关闭文件
}
return 0;
}
```
以上两段代码分别演示了如何在C++中创建和写入一个文本段落件,以及从该文件读取数据并显示。