-1

I need to read just 1 specific line from a text file using c++. The file doesn't change it's content, the lines are always the same. I need to be able to read line 37 for example, without having to read the previous 36 lines. Is this even possible?

user1913644
  • 157
  • 1
  • 11
  • 1
    Without some sort of index telling you where exactly each line begins, you cant. – Havenard Jul 29 '18 at 20:47
  • If this file is going to be read constantly like some sort of static content of your program, you can generate an index file for it containing the offset where each line begins, and then go straight there with `seekg()` as @Swordfish suggested. This should optimize the action of fetching the information. Alternatively, use one of the many database options around that will take care of that for you. They are not as simple to use but they are a lot more powerful. – Havenard Jul 29 '18 at 21:01
  • Have you heard about *string table*-s? Perhaps you should. Random hit from this site: https://stackoverflow.com/questions/14208412/static-string-literal-table – tevemadar Jul 29 '18 at 21:10

1 Answers1

1

If you know the count of characters preceeding line 37 use std::istream::seekg() to set the file pointer to the begin of line 37 and use std::getline() to read it.

OTOH, if said file never changes there is no need to read it at all. Just define the string in your code.

Swordfish
  • 12,971
  • 3
  • 21
  • 43