Home >Backend Development >C++ >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>
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
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>
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!