Floyd Davidson (and several others) pointed out that this technique is not
portable and I agree with him. Fortunately,
the project that I am working on will never be ported to other platforms.
The code that Juergan provided is (or should be) portable between GNU
ports. A very good point that Floyd made is that this technique may fail
even on the intended platform.
In the quest to find a work around, I've glanced at the source for freopen()
and fmemopen() and think that problem
_MAY_ lie inside the design of the library. If that is truly the case, then
a need for a fmemreopen function _COULD_
possibly exist. To design such a function would be totally unportable, and
definitely a time bomb, even on the intended
platform.
Before flaming me about the above paragraph, please keep in mind that I used
a lot of may's and could's as I am only
speculating without knowing the big picture. In other word's, I am only
tempting to generate discussion. Lastly, I
guess Floyd's warning is already ringing true.
Bob Steele
email: rst...@1stlink.net
Juergen Heinzl wrote:
> In article <3A4C97EB...@1stlink.net>, Bob Steele wrote:
> >Does anyone know how to redirect stdin to a memory buffer in C. I am
> >using glibc 2.2 with GCC on a Red Had 7.0 linux box.
> >
> >For example:
> >stdin=(FILE *)freopen("test.txt","r",stdin); correctly redirects stdin
> >to a file "test.txt".
> >
> >However, since there is no reopen function for memory buffers, I am
> >forced to use;
> >
> >fclose(stdin);
> >stdin=(FILE *)fmemopen(buffer,strlen(buffer),"r");
> [-]
> Works fine for me -- what's that (FILE *) for though ? You had
> better use -D_GNU_SOURCE to avoid a warning.
>
> >According to the GNU man GLIBC web pages, this should redirect stdin to
> >read input from the buffer. Unfortunately, this does not seem to work.
> >It simply returns an EOF character indicating an error condition.
> [-]
> It does, here's a slightly modified example.
>
> #include <stdio.h>
> static char buffer[] = "foobar";
>
> int
> main()
> {
> int ch;
>
> fclose(stdin);
> stdin = fmemopen (buffer, strlen (buffer), "r");
> while((ch = fgetc (stdin)) != EOF)
> printf ("Got %c\n", ch);
>
> return 0;
> }
>
> If it doesn't work for you it's a RH problem
>
> Cheers,
> Juergen
>
> --
> \ Real name : Jürgen Heinzl \ no flames /
> \ EMail Private : mono...@n-online.de \ send money instead /