Q:

Count lines in pipe stream without consume

I open a pipe stream with given cmd command:
FILE* fp = popen(cmd.c_str(), "r");

How to count its lines without consume?

I tried:
char* line = NULL;
size_t len = 0;
unsigned int lines = 0;

while(getline(&line, &len, fp) != -1){
    ++lines;
}

But it consumes fp pipe stream.

A:

I guess you are on Linux or some other POSIX system.
You basically cannot process the data from a pipe(7) (internally used by popen(3) ...) without consuming it, since pipes are non-seekable (lseek(2) would fail with ESPIPE, mmap(2) would fail with EACCESS)
You could either redirect the command to some temporary file (using lower level fork,dup2,execve syscalls(2), as explained in Advanced Linux Programming) then process that file and rewind it (and/or resend it elsewhere) or read all the data from the pipe into memory (so the available memory is a limiting factor).

