Search code examples
cunix

Using rewind() with popen()


I have a simple C code snippets as following:

#include <stdio.h>
void main() {
  FILE *f;
  char c;
  f = popen("ls", "r");
  while ((c = fgetc(f)) != EOF) {
    //Some tasks
  }
  rewind(f);
  while ((c = fgetc(f)) != EOF) {
    printf("%c", c);
  }
  fclose(f);
}

I don't know why the code output nothing. It seems the rewind() function doesn't work. Please help find out where I'm wrong. Thanks.


Solution

  • rewind is equivalent to fseek(stream, 0L, SEEK_SET) and fseek is only legal on files, not streams (which is the case with pipes).

    Check the errno after rewind it should be

    EBADF The stream specified is not a seekable stream.