Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a C string like a FILE*

Tags:

c

file-pointer

I have a C function that reads a stream of characters from a FILE*.

How might I create a FILE* from a string in this situation?

Edit:

I think my original post may have been misleading. I want to create a FILE* from a literal string value, so that the resulting FILE* would behave as though there really was a file somewhere that contains the string without actually creating a file.

The following is what I would like to do:

void parse(FILE* f, Element* result);

int main(int argc, char** argv){
    FILE* f = mysteryFunc("hello world!");
    Element result;
    parse(f,&result);
}
like image 686
math4tots Avatar asked Jul 08 '12 08:07

math4tots


3 Answers

Standard C provides no such facility, but POSIX defines the fmemopen() function that does exactly what you want.

like image 82
Keith Thompson Avatar answered Nov 16 '22 04:11

Keith Thompson


Unfortunately, C's standard library doesn't provide this functionality; but there are a few ways to get around it:

  • Create a temporary file, write your string to it, then open it for reading. If you've got POSIX, gettempnam will choose a unique name for you

  • The other option (again for POSIX only) is to fork a new process, whose job will be to write the string to a pipe, while you fdopen the other end to obtain a FILE* for your function.

  • As @KeithThompson pointed out, fmemopen does exactily what you want, so if you have POSIX, use that. On any other platform, (unless you can find the platform-equivalent), you'll need a temporary file.

like image 9
Dave Avatar answered Nov 16 '22 04:11

Dave


Last time I had this kind of problem I actually created a pipe, launched a thread, and used the thread to write the data into the pipe... you would have to look into operating system calls, though.

There are probably other ways, like creating a memory mapped file, but I was looking for something that just worked without a lot of work and research.

EDIT: you can, of course, change the problem to "how do I find a nice temporary filename". Then you could write the data to a file, and read it back in :-)

like image 3
Christian Stieber Avatar answered Nov 16 '22 04:11

Christian Stieber