I have a program in C++ that needs to return a line that a specific word appears in. For instance, if my file looks like this:
the cow jumped over
the moon with the
green cheese in his mouth
and I need to print the line that has “with”. All the program gets is the offset from the beginning of the file (in this case 24, since “with” is 24 characters from the beginning of the file).
How do I print the whole line “the moon with the”, with just the offset?
Thanks a lot!
A good solution is reading the file from the beginning until the desired position (answer by @Chet Simpson). If you want optimization (e.g. very large file, position somewhere in the middle, typical lines rather short), you can read the file backwards. However, this only works with files opened in binary mode (any file on unix-like platforms; open the file with
ios_base::binaryparameter on Windows).The algorithm goes as follows:
Code (tested on Windows):
Edit: On Windows-like platforms, where end-of-line is marked by
\r\n, since you have to use binary mode, the output string will contain the extra character\r(unless there is no end-of-line at end-of-file), which you can throw away.