Memory pointer cast to FILE* ?

Started by
5 comments, last by GameDev.net 17 years, 9 months ago
Hello all, Is there a method of converting a memory-buffer pointer (e.g. char*) to a stdio FILE* pointer? Is "file/pipe redirection" what I'm looking for? I've come across a few *nix sites on how to do something similar from the commandline, but I'm really looking for source examples. Thanks, - m³
Advertisement
Not in standard C. However, there's not much reason to as you can use in-memory versions of all the file I/O functions. ex: sscanf() instead of fscanf().
The way I implement this is to write your own file API that when in "real" file mode can read off disk directly (in this case it just maps directly to the windows file IO functions), but that can also be used to read from RAM-disks. E.g.:

MyFileHdl file1,file2;file1=MyFile::Fopen("file.txt",flags);//Maps to fopen or another suitable windows file APifile2=MyFile::Fopen(pBuffer,bufferSize);//Maps to my own simple ram disk libraryfile1->Read(pPtr,12); //Calls freadfile2->Read(pPtr,12); //Calls memcpy and increments internal pointer to buffer
Dear god no.

What are you *really* trying to do?
Quote:Original post by Zahlman
Dear god no.


Not quite sure what so terrible about that solution :) As I said most of the projects I've worked on have used this solution (or a C-based version of it). It has many advantages (it allows abstraction of the file system to allow for platform differences, and for support for pak/zip files without changing your code). There is a virtual function overhead, but thats generally pretty trivial compared to the file system access time. It also allows for an easy to use wrapper around ascynchronous file calls.
Quote:Original post by griffin2000
The way I implement this is to write your own file API that when in "real" file mode can read off disk directly (in this case it just maps directly to the windows file IO functions), but that can also be used to read from RAM-disks. E.g.:

*** Source Snippet Removed ***


Your code looks suspiciously like C++. The standard library of the C++ language contains iostreams, which already provide what you need (see the fstream and sstream headers). Do you have any reasons to reimplement this?
Assuming you're using C and not C++, opening pipe (or whatever your OS supports) would work. In *nix you could use pipe() to make the pipe and fdopen() to convert them to FILE*, then you need a way to write while reading (fork/thread, or maybe the stuff that needs the FILE* can be made to read in pieces so you could do both from same process/thread). Or you could write a temporary file if pipes are not usable.

This topic is closed to new replies.

Advertisement