1

I don't want any boost dependency or anything external. I could read the file line by line, and process each line separately. But if it works better, I can also load the whole file in memory, and process it line by line afterwards.

What's the best approach? Also, what is the fastest approach, how do they differ?

Also, this should both work with a regular text file, and piping a file through terminal.

Ron
  • 14,674
  • 4
  • 34
  • 47
Baron Yugovich
  • 3,843
  • 12
  • 48
  • 76
  • I found this reference on using ifstream, but without enough details https://lemire.me/blog/2012/06/26/which-is-fastest-read-fread-ifstream-or-mmap/ – Baron Yugovich Jan 31 '18 at 15:10
  • 1
    Do you want the best approach or the fastest way? You probably can't have both. – nwp Jan 31 '18 at 15:14
  • 1
    why do you need to read line by line? Reading all the file contents as a whole and then processing line by line will most likely be faster – 463035818_is_not_an_ai Jan 31 '18 at 15:14
  • See also: https://stackoverflow.com/q/31162367/10077 – Fred Larson Jan 31 '18 at 15:27
  • @UKMonkey Oh you didn't know? They shouldn't learn, they should just DISAPPEAR from this holy website - Of course I'm kidding. But that's how a big part of SO users behave. – Arkoudinos Feb 01 '18 at 12:00
  • This question is not a duplicate. OP is asking the *fast* way, but the suggested duplicate is about just reading "line by line"... – starriet Aug 19 '22 at 15:16

1 Answers1

8

Just use std::getline. Pretty straightforward solution:

std::ifstream file("filePath");
std::string line;
while (std::getline(file, line)) {
    // line contains the current line
}
Maroš Beťko
  • 2,181
  • 2
  • 16
  • 42
  • Thanks. How would that change if I have to read through pipe, i.e. piping a text file through terminal? – Baron Yugovich Jan 31 '18 at 15:20
  • 1
    @BaronYugovich: If you're just piping into stdin, just use something like `std::getline(std::cin, line)`. – Fred Larson Jan 31 '18 at 15:23
  • Just FYI, this code itself is far from "fastest". Actually, it is *very slow*. OP is asking the fast way. Since IO takes a long time, one should load as much data as possible into the memory at once. – starriet Aug 19 '22 at 15:13