c++如何删除,修改文件中某行内容
时间: 2023-06-14 09:06:23 浏览: 572
要删除或修改文件中的某一行内容,需要进行以下步骤:
1. 打开文件,并将文件内容读入到一个字符串向量中。
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
void readFile(std::string fileName, std::vector<std::string>& content) {
std::ifstream file(fileName);
if (!file.is_open()) {
std::cerr << "Cannot open the file: " << fileName << std::endl;
return;
}
std::string line;
while (std::getline(file, line)) {
content.push_back(line);
}
file.close();
}
```
2. 删除或修改文件中的某一行内容。
```c++
void deleteLine(std::vector<std::string>& content, int lineNum) {
content.erase(content.begin() + lineNum);
}
void modifyLine(std::vector<std::string>& content, int lineNum, std::string newLine) {
content[lineNum] = newLine;
}
```
3. 将修改后的向量中的内容写回到文件中。
```c++
void writeFile(std::string fileName, std::vector<std::string>& content) {
std::ofstream file(fileName);
if (!file.is_open()) {
std::cerr << "Cannot open the file: " << fileName << std::endl;
return;
}
for (const auto& line : content) {
file << line << std::endl;
}
file.close();
}
```
下面是完整的代码示例:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
void readFile(std::string fileName, std::vector<std::string>& content) {
std::ifstream file(fileName);
if (!file.is_open()) {
std::cerr << "Cannot open the file: " << fileName << std::endl;
return;
}
std::string line;
while (std::getline(file, line)) {
content.push_back(line);
}
file.close();
}
void deleteLine(std::vector<std::string>& content, int lineNum) {
content.erase(content.begin() + lineNum);
}
void modifyLine(std::vector<std::string>& content, int lineNum, std::string newLine) {
content[lineNum] = newLine;
}
void writeFile(std::string fileName, std::vector<std::string>& content) {
std::ofstream file(fileName);
if (!file.is_open()) {
std::cerr << "Cannot open the file: " << fileName << std::endl;
return;
}
for (const auto& line : content) {
file << line << std::endl;
}
file.close();
}
int main() {
std::vector<std::string> content;
std::string fileName = "test.txt";
readFile(fileName, content);
// 删除第3行内容
deleteLine(content, 2);
// 修改第5行内容
modifyLine(content, 4, "This is a new line.");
writeFile(fileName, content);
return 0;
}
```