Home > Backend Development > C++ > body text

Can You Directly Jump to a Specific Line in a Text File Using C fstream?

Patricia Arquette
Release: 2024-11-01 12:58:29
Original
700 people have browsed it

Can You Directly Jump to a Specific Line in a Text File Using C   fstream?

Seeking a Specific Line in Text File with C

With the fstream library in C , it becomes convenient to read and write to text files. However, directly navigating to a specific line can be challenging. This question explores a potential solution to this problem.

Problem:

If a text file is opened using fstream, is there a straightforward way to jump to a particular line, such as line 8?

Answer:

Although fstream provides a way to set the seek pointer of the file, it directly does not allow jumping to a specific line. A practical approach is to loop through the file, ignoring all lines until the desired line is reached. Here's how it can be achieved:

<code class="cpp">std::fstream& GotoLine(std::fstream& file, unsigned int num) {
    file.seekg(std::ios::beg);
    for (int i = 0; i < num - 1; ++i) {
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return file;
}</code>
Copy after login

This function takes the file and the line number that it should seek to and returns the file object.

Example:

Consider a text file with the following content:

1
2
3
4
5
6
7
8
9
10
Copy after login

The following C program demonstrates how to use the GotoLine function:

<code class="cpp">int main() {
    using namespace std;
    fstream file("bla.txt");

    GotoLine(file, 8);

    string line8;
    file >> line8;

    cout << line8;
    cin.get();
    return 0;
}</code>
Copy after login

Output:

8

In this example, the program reads the eighth line of the text file and prints the content, which is "8".

The above is the detailed content of Can You Directly Jump to a Specific Line in a Text File Using C fstream?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!