假设下图这是一个10万多字的文章,有很多③部分的内容,我们想要将它的段落全部删除,但是在word和pdf修改器中都没法删除,就可以运用代码帮助了
#include <iostream>
#include <fstream>
#include <string>
void removeParagraphAfterMarker(const std::string& inputFilePath, const std::string& outputFilePath, const std::string& marker) {
std::ifstream inputFile(inputFilePath);
std::ofstream outputFile(outputFilePath);
if (!inputFile.is_open() || !outputFile.is_open()) {
std::cerr << "Error opening file!" << std::endl;
return;
}
std::string line;
bool skipParagraph = false;
// 逐行读取文件
while (std::getline(inputFile, line)) {
if (line.find(marker) != std::string::npos) {
skipParagraph = true; // 标记段落开始
continue;
}
if (skipParagraph) {
// 如果当前段落应该被跳过
if (line.empty()) {
skipParagraph = false; // 下一段不跳过
}
continue;
}
// 写入有效段落到输出文件
outputFile << line << std::endl;
}
inputFile.close();
outputFile.close();
}
int main() {
std::string inputFilePath = "/home/ljw/删除③/dd.txt"; // 输入文件路径
std::string outputFilePath = "/home/ljw/删除③/dd_cleaned.txt"; // 输出文件路径
std::string marker = "③"; // 要删除的段落标记
removeParagraphAfterMarker(inputFilePath, outputFilePath, marker);
std::cout << "Processing complete. Output saved to " << outputFilePath << std::endl;
return 0;
}
将这段代码转换为适用于 Windows 系统的版本,主要需要调整文件路径的格式。在 Windows 系统中,路径通常使用反斜杠(\
),而不是 Linux 系统中的正斜杠(/
)。此外,由于反斜杠在 C++ 中是转义字符,因此需要使用双反斜杠(\\
)来表示路径分隔符。
以下是修改后的代码,适用于 Windows 系统:
#include <iostream>
#include <fstream>
#include <string>
void removeParagraphAfterMarker(const std::string& inputFilePath, const std::string& outputFilePath, const std::string& marker) {
std::ifstream inputFile(inputFilePath);
std::ofstream outputFile(outputFilePath);
if (!inputFile.is_open() || !outputFile.is_open()) {
std::cerr << "Error opening file!" << std::endl;
return;
}
std::string line;
bool skipParagraph = false;
// 逐行读取文件
while (std::getline(inputFile, line)) {
if (line.find(marker) != std::string::npos) {
skipParagraph = true; // 标记段落开始
continue;
}
if (skipParagraph) {
// 如果当前段落应该被跳过
if (line.empty()) {
skipParagraph = false; // 下一段不跳过
}
continue;
}
// 写入有效段落到输出文件
outputFile << line << std::endl;
}
inputFile.close();
outputFile.close();
}
int main() {
std::string inputFilePath = "C:\\Users\\YourUsername\\Documents\\dd.txt"; // 输入文件路径
std::string outputFilePath = "C:\\Users\\YourUsername\\Documents\\dd_cleaned.txt"; // 输出文件路径
std::string marker = "③"; // 要删除的段落标记
removeParagraphAfterMarker(inputFilePath, outputFilePath, marker);
std::cout << "Processing complete. Output saved to " << outputFilePath << std::endl;
return 0;
}
/
)替换为双反斜杠(\\
)。
C:\\Users\\YourUsername\\Documents\\dd.txt
和 C:\\Users\\YourUsername\\Documents\\dd_cleaned.txt
,请根据实际情况替换 YourUsername
和文件路径。
确保输入文件路径和输出文件路径是正确的,并且程序有权限访问这些路径。
如果文件路径较长或包含特殊字符,建议使用原始字符串字面量(R"(path)"
),例如:
std::string inputFilePath = R"(C:\Users\YourUsername\Documents\dd.txt)";
std::string outputFilePath = R"(C:\Users\YourUsername\Documents\dd_cleaned.txt)";
这样可以避免手动处理双反斜杠。
进行这些操作
dd_cleaned.txt就是改写成的文件