Hello all, I need to be able to seek through a stream. This is a non-file stream, created by a pipe between my program and a subprogram, more specifically, created by the "popen()" function. Seeking position markers in a file stream is pretty easy, but it does not seem to be as straightforward with this kind of stream.
So far, I have tried the rewind() and fseek() functions, but these do not work (the first character scanned after a call to rewind() should be the first character in the stream again, but instead results in a EOF (and I know the stream was not empty)).
Is there something else I need to be doing, or are these types of streams (ones created by popen()) un-seekable?
Thanks for any help.
Here is a sample of the code I am using:
Code:
int
main(void)
{
int num_lines;
FILE *streamp;
streamp = popen(COMMAND, "r");
//pass stream onto function
num_lines = get_num_lines(streamp);
//prints "10" in the specific case I am using, so I know stream is not empty.
printf("%d", num_lines);
//RESET marker to beginning of stream (I had hoped)
rewind(streamp);
//instead this indicated that the marker was still at the end of the stream
if( fgetc(streamp) == EOF)
printf("END");
}
int
get_num_lines(FILE *streamp)
{
int num_lines = 0;
char ch, prev = NEWLINE;
while((ch = fgetc(streamp)) != EOF)
{
if(ch == NEWLINE)
{
++num_lines;
}
prev = ch;
}
if(prev != NEWLINE)
{
++num_lines;
}
return(num_lines);
}