C++学习进阶版(二):与文件相关的函数用法

目录

1、读取文件的指定行

(1)main函数中直接读

(2)封装成函数

① 无返回值类型

② 直接返回读取的内容

2、求文件的行数

3、文件内容读取成一个字符串


1、读取文件的指定行

(1)main函数中直接读

#include <iostream>
#include <fstream>
#include <string>

int main() {
    // 要读取的行号,例如第5行
    int line_number = 5;
    int i = 0; 
    std::ifstream file("G:/MyCode/c++/test.dump");

    if (file.is_open()) {
        std::string line;
        // 从1开始计数,因为行号通常是从1开始的
        while (std::getline(file, line)) {
            ++i;
            if (i == line_number) {
                // 成功读取了目标行
                std::cout << "Line " << line_number << ": " << line << std::endl;
                break; // 找到目标行后退出循环
            }
        }
        if (i != line_number) {
            std::cerr << "Could not find line " << line_number << std::endl;
        }

        file.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}

(2)封装成函数

① 无返回值类型

#include <iostream>
#include <fstream>
#include <string>

// 函数声明,只接受行号 n 作为参数
void readSpecificLineFromFile(int n);

int main() {
    int line_number = 5; // 要读取的行号
    readSpecificLineFromFile(line_number);
    return 0;
}

// 函数定义,读取并输出第 n 行的内容
void readSpecificLineFromFile(int n) {
    std::ifstream file("G:/MyCode/c++/test.dump");
    int current_line = 0;
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            ++current_line;
            if (current_line == n) {
                std::cout << "Line " << n << ": " << line << std::endl;
                file.close();
                return;
            }
        }
        std::cerr << "Could not find line " << n << std::endl;
        file.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }
}

② 直接返回读取的内容

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

// 函数声明,只接受行号 n 作为参数
std::string readLineFromFile(int n);

int main() {
    int line_number = 5; // 要读取的行号
    std::string line= readLineFromFile(line_number);
    cout << line <<endl;
    return 0;
}


// 函数定义,读取并输出第 n 行的内容
std::string readLineFromFile(int n) {
    std::ifstream file("G:/MyCode/c++/test.dump");
    int current_line = 0;
    std::string line;
    std::string lineContent;
    if (!file.is_open()) {
        std::cerr << "Unable to open file" << std::endl;
        return ""; // 返回空字符串表示文件无法打开
    }
    while (std::getline(file, line)) {
        ++current_line;
        if (current_line == n) {
            lineContent = line;
            break;
        }
    }
    file.close(); // 确保文件被关闭

    return lineContent; // 返回找到的行内容,或空字符串表示未找到
}

2、求文件的行数

#include <iostream>
#include <fstream>
#include <string>

// 函数声明
int countLines(const std::string& filename);

int main() {
    int lineCount = countLines("1.dump");
    if (lineCount > 0) {
        std::cout << "The file '1.dump' has " << lineCount << " lines." << std::endl;
    } else {
        std::cerr << "The file '1.dump' could not be opened or is empty." << std::endl;
    }
    return 0;
}

// 函数定义
int countLines(const std::string& filename) {
    std::ifstream file(filename);
    int lineCount = 0;

    // 检查文件是否成功打开
    if (file) {
        std::string line;
        // 逐行读取文件直到文件末尾
        while (std::getline(file, line)) {
            ++lineCount;
        }
    } else {
        // 如果文件无法打开,返回0表示没有行
        lineCount = 0;
    }

    // 关闭文件
    file.close();

    // 返回文件的行数
    return lineCount;
}

3、文件内容读取成一个字符串

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>

// 函数声明,读取文件并将其内容合并为一个字符串
std::string readAndConcatenateDumpFile(const std::string& filename);

int main() {
    try {
        std::string filename = "1.dump";  // 文件路径
        std::string fileContents = readAndConcatenateDumpFile(filename);
        
        // 打印文件内容,这里仅打印前100个字符作为示例
        std::cout << "Contents of file '" << filename << "':" << std::endl;
        std::cout << fileContents << std::endl;

    } catch (const std::runtime_error& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;  // 非正常退出,返回错误码
    }

    return 0;  // 正常退出
}

// 函数定义,读取文件并将其内容合并为一个字符串
std::string readAndConcatenateDumpFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("Failed to open the dump file.");
    }
    std::stringstream ss;
    std::string line;

    while (std::getline(file, line)) {
        ss << line;
    }
    file.close();
    return ss.str();
}

最近在用C++写指令文件的解码和状态机转换,其中的一些函数,供大家参考。

后续相关的会更新在文章中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值