I have a function which reads data from a file (i.e. it is passed a FILE*).
What I want to accomplish is to use that function for reading the data from a string, i.e. I would like to treat the data in the string as if it were data in a physical file (e.g. using fgets, fseek etc.), so in effect, a memory file.
I tried to associate the data string with a /dev/null (NUL) file via setvbuf (similar to what I read in this stackoverflow question), but either I did it wrong or that's not how it's done.
Can somebody help me achieving this in C, preferably in a portable fashion (actually, I don't mind using OS-specific functions/ifdefs as long as it works and it's not /too/ complicated).
Edit:
#include <stdio.h>
#include <string.h>
#define NULL_L "/dev/null"
#define NULL_W "NUL"
FILE* open_memfile(char *pc_file_as_string) {
FILE *f = fopen(NULL_L, "rb");
int i_size = strlen(pc_file_as_string);
setvbuf(f, pc_file_as_string, _IOLBF, i_size);
return f;
}
int main()
{
char c_line[100] = "";
char pc_file_as_string[] = "line1 asdf\nline2 fsa afds\n\nline4";
FILE *f = open_memfile(pc_file_as_string);
int i = 4;
while (i > 0) {
fgets(c_line, 100, f);
if (c_line == NULL)
break;
else
puts(c_line);
i--;
}
fclose(f);
return 0;
}