ofstream在写入时怎么判断该字符串已经写入过而不重复写入
时间: 2024-05-05 22:15:38 浏览: 16
在写入文件之前,可以先读取文件内容,判断该字符串是否已经存在于文件中。如果不存在,就可以将该字符串写入文件中。如果已经存在,就可以跳过该字符串的写入,避免重复写入。可以使用std::ifstream和std::stringstream来读取文件内容,并使用std::string的find函数来判断字符串是否已经存在于文件中。以下是示例代码:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string filename = "test.txt";
string str = "Hello, World!";
// 读取文件内容
ifstream in(filename);
stringstream buffer;
buffer << in.rdbuf();
string file_content = buffer.str();
// 判断字符串是否已经存在于文件中
if (file_content.find(str) == string::npos) {
// 字符串不存在,可以写入文件
ofstream out(filename, ios::app);
out << str << endl;
cout << "写入成功!" << endl;
} else {
// 字符串已经存在,跳过写入
cout << "字符串已经存在,无需写入。" << endl;
}
return 0;
}
```