Read a particular line in a text file

Hi all

Firstly, many thanks for the members here who have actively helping me before.

I have a task to do and I have no idea how to implement it using C++.

What I want to achieve is:

1. Read a text file, which may have 1000+ lines
2. find a line in it, which contains the word 'fail', so it maybe in the very beginning of the text file, or the end, no idea.
3. Let say it is the 564th line (I think I can do a counting in a while loop getline to keep track of the line number)
4. I then have to go back 10 lines and copy the lines from this point, and save in another file.

So here is why I am struggling, how can I access a line in a text file by line number please???

Many thanks again for all the help.
I would recommend reading each line of the file into a std::vector and then do your searching through the vector.

Trying to access a text file by line number gets tricky because line sizes probably vary. You'll need to keep track of the file position where each line starts within the file so you can seek to that position.
is it feasible to store a text file of size 3mb into a vector??
is it feasible to store a text file of size 3mb into a vector??

Yes, it's feasible. Nowadays many files, such as digital images are larger than that and can be loaded into memory.

Sometimes I will code a program in more than one way, trying different ideas. Storing the entire file in a vector would probably be the simplest, and the one I'd try first. There are other options, one has been mentioned, that is to store the start position in the file of each line. Another possibility is to use a buffer to store just the most recent ten or so lines from the file, rather than the entire file. This requires much less storage, but might require a bit more effort to get right.
You are quite right, I think I can decide the maximum buffer I need to store some lines temporary!! and I just have to work with this array!!

Silly me, thanks for the advice! love this forum, members are so helpful!
Topic archived. No new replies allowed.