C++ Guide: Read Specific File Lines

In C++, you cannot directly specify jumping to a specific line in a file. You need to read the file content line by line and make a judgement to reach a specific line. Below is an example code showing how to achieve this functionality:

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

int main() {
    std::ifstream file("example.txt");
    std::string line;
    int target_line = 5; // 指定跳转到第5行

    if (file.is_open()) {
        int current_line = 1;

        while (getline(file, line)) {
            if (current_line == target_line) {
                std::cout << "第" << target_line << "行的内容为: " << line << std::endl;
                break;
            }

            current_line++;
        }

        file.close();
    } else {
        std::cout << "无法打开文件" << std::endl;
    }

    return 0;
}

In the example above, we opened a file named example.txt and specified to jump to the 5th line. We read the file content line by line, counting the current line number. When the count equals the target line number, we print the line content and exit the loop.

Please note that in actual application, you may need to do more error handling and fault tolerance for issues such as file existence and read errors.

bannerAds