Possible Duplicate:
In C++ is there a way to go to a specific line in a text file?
Whats the smarter way to read specific set of lines (line number A to line number B) from a text file in C++ using standard C++ library (without opting to Boost)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the line length isn’t fixed and you don’t have an index you can’t do better than counting the
\ns.Consider this example file:
Line 1 starts at byte 0, Line 2 at 6, Line 3 at 22, Line 4 at 28, Line 5 at 49 and Line 6 at 50 – there’s no pattern.
If we knew that information in advance, e.g. at the beginning of the file we had that information in some table we could compute a byte offset into the file for the lines we cared about and use a seek to jump straight there.
If the line width is fixed at 20 bytes:
Then we can compute the start of a line as a simple multiplication – an offset into the file.
If you’re looking for a “generic” way of doing this I’d suggest something like:
This is appropriate for small-ish files (it reads the entire file into a
std::string). For larger files you might want do do the same, but withmmapinstead, using the mapped region as iterators. Or you could do this with aRandomAccessiterator that usesseek()within the file. (std::istream_iteratordoes not do this, it’s only aForwardIteratorso wouldn’t be appropriate).