Problem with fstat() after fmemopen()
Alexander Lamaison
awl03@doc.ic.ac.uk
Wed Apr 15 23:42:00 GMT 2009
Hello everyone,
I've been trying to use fmemopen() to open a string. This is in order
to pass it to a program that expects a FILE *. However, I've found
that calling fstat using the returned stream's file descriptor fails
with errno 9, "Bad descriptor". Other operations, such as reading and
seeking, work fine.
fmemopen() returns a FILE whose fd is set to -2 (obviously invalid)
which fstat() dislikes very much. Is fstatting an fmemopened stream
intended not to work? If so, the documentation doesn't mention it at
all. Much of the appeal of using fmemopen to fake a real file seems
to go away if the client program has to treat it specially.
This code demonstrates the problem:
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
static char buffer[] = "foobar";
int
main (void)
{
int ch;
FILE *stream;
struct stat st;
int rc;
stream = fmemopen(buffer, strlen (buffer), "r");
if (stream == NULL)
{
perror("fmemopen() failed");
exit(1);
}
rc = fstat(fileno(stream), &st);
if (rc == -1)
{
perror("fstat() failed");
exit(1);
}
while ((ch = fgetc(stream)) != EOF)
printf("Got %c\n", ch);
fclose(stream);
return 0;
}
What do you guys think?
Alex Lamaison
More information about the Libc-help
mailing list