用c++编程实现使用I/O输出流以文本方式打开一个文件名为test.txt的文件,在文件后面添加字符“已成功添加该字符!”,然后读出整个文件的内容显示出来,看看是否正确
时间: 2024-02-27 09:54:13 浏览: 20
好的,可以使用如下C++代码实现:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// 定义文件名和要写入的字符串
string fileName = "test.txt";
string content = "已成功添加该字符!";
// 使用IO输出流以文本方式打开文件,向文件后面添加字符串
ofstream outFile(fileName, ios::app);
if (outFile.is_open()) {
outFile << content;
outFile.close();
cout << "成功向文件" << fileName << "写入数据!" << endl;
} else {
cout << "打开文件" << fileName << "失败!" << endl;
return -1;
}
// 读取整个文件的内容并显示出来
ifstream inFile(fileName);
if (inFile.is_open()) {
string line;
cout << "文件" << fileName << "的内容为:" << endl;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "读取文件" << fileName << "失败!" << endl;
return -1;
}
return 0;
}
```
以上代码会在文件test.txt后面添加字符“已成功添加该字符!”,并读取整个文件的内容并输出到控制台上。请确保在运行代码前已经创建了test.txt文件。