-1

I have a stream like so:

FILE *fp;
byte *buf;
size_t len;
fp = open_memstream(&buf, &len);

I write some bytes into it.

Now I want loop from the beginning of the stream to the end. I have a method that that does something like this

void method(FILE *fp)
{
   while(!feof(fp)){
     fread(Buffer, sizeof(byte), BUFSIZE, fp);
   }
}

But the while loop never stops. I also explicity tried to write EOF char to fp but feof did not work. What's going on here?

Aman
  • 773
  • 2
  • 10
  • 22
  • What are you doing inside the `while` loop that will make the stream be at the end? – Iharob Al Asimi Feb 21 '15 at 02:13
  • I am using fread fread(Buffer, sizeof(byte), BUFSIZE, fp); – Aman Feb 21 '15 at 02:14
  • so, didn't you think of `while (fread(Buffer, sizeof(byte), BUFSIZE, fp) > 0)`? Note, that `EOF` is a marker that will not be set until you try to `fread()` beyond the end of the file, so in the best case you will have one extra iteratin. But you already ignore the return value of `fread()` everyone seems to ignore the return value of functions... – Iharob Al Asimi Feb 21 '15 at 02:17
  • Very good point but I'm curious why feof is not registering the EOF char that I have explicitly written to stream? – Aman Feb 21 '15 at 02:19
  • 1
    Because `EOF` is not a `char`. It's `-1` what char is that? – Iharob Al Asimi Feb 21 '15 at 02:19
  • so what does it mean when I write EOF to a stream? Does it not write anything to it? – Aman Feb 21 '15 at 02:20

1 Answers1

1

The real problem is that you are using the wrong function, you can't read from a stream created with open_memstream() that's meant for writing only, what you need is

FILE *fp = fmemopen(buffer, size, "r");

this way you can read from buffer as if it was a FILE * stream.

Also, EOF is not a char, not because for example getchar() returns EOF that means it's a character, it's actually a special value that indicates the EOF.

And in fact while (!feof(file)) is always wrong.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97