This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Problem with fstat() after fmemopen()


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]