Read File from Line in C++ Using fread

In C++, the fread function is used to read data from a file, specifically for reading binary files. If you need to read from a specific line in the file, you can first locate the position of that line and then call the fread function to perform the reading operation.

Here is a simple example code that demonstrates how to read file contents from a specified line:

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main() {
    ifstream file("example.txt", ios::binary); // 打开文件

    if (!file.is_open()) {
        cout << "无法打开文件!" << endl;
        return 1;
    }

    int line = 3;   // 指定要读取的行数
    int lineSize = 256; // 假设每行最大长度不超过256个字符

    file.seekg(0, ios::beg); // 将文件指针定位到文件开头

    for (int i = 1; i < line; i++) {
        file.ignore(lineSize, '\n'); // 忽略前面的行
    }

    char buffer[lineSize];
    file.read(buffer, lineSize); // 读取指定行的内容

    cout << "第" << line << "行的内容是:" << buffer << endl;

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

    return 0;
}

In the example above, we opened a text file named example.txt first, then positioned the file pointer to the beginning of the file using the seekg function. Next, we skipped the previous lines using the ignore function, finally, we read the content of the specified line using the read function and output it to the console.

Please note that the variable lineSize in the above code represents the maximum length of each line, and should be adjusted according to actual requirements. Additionally, the above example is only applicable for text files. If you need to read binary files, you can set the open mode of ifstream to ios::binary.

bannerAds