2

Is there a way to get the current line without advancing the position in the file?

I have an iterator for files that only calls getline() when operator*() is called to avoid needless copying of lines into strings. The iterator simply moves the position with file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); every time operator++ is called, however, this causes a line to be skipped when calling operator*, as that uses getline(). Therefore I would like to somehow get the current line but not advance the reading position. Is there a built in function that does this?

lo tolmencre
  • 3,804
  • 3
  • 30
  • 60
  • 2
    If it's a real file, and not a pipe or something, use `tellg()` to obtain the file position before `getline()`, then `seekg()` back to it. – Sam Varshavchik Feb 21 '17 at 01:50
  • 2
    Call `getline` in the `operator++` function instead? And of course on iterator construction. Then the `operator*` function just returns the current line. – Some programmer dude Feb 21 '17 at 01:50
  • @Someprogrammerdude but I don"t want to copy needlessly. @SamVarshavchik I suspected `seekg` to have linear complexity, as "seek" kind of suggests that it does a search for the position. Is `seekg` cheap enough to do that every time `operator*` is called? – lo tolmencre Feb 21 '17 at 01:53
  • 1
    Copy *what*? I don't see any need for any copying. – Some programmer dude Feb 21 '17 at 01:55
  • @Someprogrammerdude copying the line into a string: `getline(file, string)` – lo tolmencre Feb 21 '17 at 01:56
  • Oy vey. Instead of attempting to guess what a method does solely based on its name, you should instead invest some time reading the documentation, reading a good C++ book, and reading a good book on operating systems, that explain how they work. – Sam Varshavchik Feb 21 '17 at 01:57
  • 1
    But you do that now too, in the dereference operator, don't you? Or do you mean that you don't have the line as a member variable? Perhaps it should be then? – Some programmer dude Feb 21 '17 at 01:57
  • @Someprogrammerdude yes, but *only* there, not every time `operator++` is called. – lo tolmencre Feb 21 '17 at 01:58
  • 3
    If you use `ignore` to skip past the current line in the increment operator, you actually scan all characters in the file to be able to compare them to the newline. Instead of scanning and comparing you will scan and copy if you use `getline` instead. Complexity- and efficiency-wise there's really not much difference. *And* it will solve your problem. Go with simplicity and working code *first*, then if really needed (seldom and definitely not in your case) start pondering about optimizations. – Some programmer dude Feb 21 '17 at 02:01
  • ah, ok, I see. Thanks. – lo tolmencre Feb 21 '17 at 02:02
  • Related: [C++ fstream function that reads a line without extracting?](https://stackoverflow.com/q/10268872/3258851) – Marc.2377 May 17 '18 at 06:45

0 Answers0