c++删除文本内容
时间: 2023-12-03 14:01:58 浏览: 29
你可以使用C++的文件流和字符串操作来删除文本内容。以下是一个示例代码,它打开一个文件,删除其中的某些行,并将剩余内容写回到同一文件中:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file_in("example.txt");
std::ofstream file_out("example.txt.tmp");
std::string line;
int line_number = 0;
while (std::getline(file_in, line)) {
line_number++;
if (line_number == 2 || line_number == 4) {
continue; // skip lines 2 and 4
}
file_out << line << std::endl;
}
file_in.close();
file_out.close();
std::remove("example.txt");
std::rename("example.txt.tmp", "example.txt");
return 0;
}
```
在这个示例中,我们打开名为`example.txt`的文件,并逐行读取其中的内容。如果读取到的行是需要删除的行,我们就跳过它并继续读取下一行。如果读取到的行不是需要删除的行,我们就将它写入名为`example.txt.tmp`的临时文件中。完成后,我们关闭原文件和临时文件,使用`std::remove`函数删除原文件,再使用`std::rename`函数将临时文件重命名为原文件。这样就完成了删除文本内容的操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)