C++读取写入文件指定行数

指定行数读取文件

指定行数写入文件


废话不多说,直接看源代码:


#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


以上就是源代码了,报错了来找我,我来给你补😡😡

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值