指定行数读取文件
指定行数写入文件
废话不多说,直接看源代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 读取文件中的第四行
bool readLine(const std::string& filename, std::string& fourthLine,int lineT=5) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return false;
}std::string line;
int lineCount = 1;while (std::getline(file, line) && lineCount < 4) {
++lineCount;
}if (lineCount == lineT) {
fourthLine = line;
file.close();
return true;
}file.close();
return false;
}
bool replaceLine(const std::string& filename, const std::string& newContent,int lineT = 1) {
std::ifstream originalFile(filename);
std::ofstream tempFile("temp.txt");if (!originalFile.is_open() || !tempFile.is_open()) {
std::cerr << "打开文件失败" << std::endl;
return false;
}std::string line;
int lineCount = 0;//逐行读取原始文件并写入临时文件,直到第四行
while (std::getline(originalFile, line)) {
if (++lineCount == lineT) tempFile << newContent << std::endl;
else tempFile << line << std::endl;
}//关闭文件
originalFile.close();
tempFile.close();//删除原始文件并重命名临时文件
std::remove(filename.c_str());
std::rename("temp.txt", filename.c_str());return true;
}
//Example Using function
int main() {
std::string filename = "example.txt";
std::string newLineContent = "This is the new contene.";
std::string fileContent;
replaceLine(filename,newLineContent,4) ? printf("1"):printf("0");
readLine(filename,fileContent,4);
cout << fileContent;
return 0;
}
//--Hello LenXing-- You shouldn't getfor my name!
//This is for example --by 冷心 Please using string
以上就是源代码了,报错了来找我,我来给你补😡😡