An easy way to replace fread()'s with reading from a byte array?
Question
I have a piece of code that needs to be run from a restricted environment that doesn't allow stdio (Flash's Alchemy compiler). The code uses standard fopen/fread functions and I need to convert it to read from a char* array. Any ideas on how to best approach this? Does a wrapper exist or some library that would help?
Thanks!
EDIT: I should also mention that it's reading in structs. Like this:
fread(&myStruct, 1, sizeof(myStruct), f);
Solution
I don't know of any such wrapper, but I don't think it would be too difficult to make your own. That's because C's approach to file I/O hides everything behind the FILE*
interface, which actually makes it nicely object-oriented.
Since you're using C rather than C++, I would suggest using preprocessor macros to replace every instance of fopen()
, fclose()
and fread()
with MEM_fopen()
etc. which are routines that you will define. You will need to define your own FILE
type, for which you could simply use the following:
typedef unsigned char *FILE;
(If you need to manage EOF, you will instead need FILE
to be a struct
with an additional length
field.)
Then your MEM_fread()
function will look something like:
int MEM_fread(unsigned char *buf, size_t size, size_t n, FILE *f) {
memcpy(buf, *f, size * n);
*f += size * n;
return n;
}
The signature for the MEM_fopen()
"constructor" may need to change slightly, since the identifier you need is now a memory address instead of a filename.
OTHER TIPS
glibc has fmemstream
, open_memstream
, and open_wmemstream
which all return a FILE * that you can use with the stdio file IO functions directly and also call fclose on.
man 3 fmemopen
Is memcpy
insufficient? It should be pretty easy to write a wrapper around it that has a signature similar to fread
.
Just write your own version of fread(). Pass the .obj or .lib to the linker before the CRT library and the linker will pick your definition instead of the one from the CRT library.