I'm trying to interpose fscanf
function that originally reads from stdin
like fscanf(stdin,"%ms", &secret)
. In my interposed function, I'm trying to make it to read from an input file that I created with character string. Following is what I'm doing:
int fscanf(FILE *stream, const char *format, ...){
FILE * in ;
char * buffer = "secretString";
size_t length = strlen(buffer);
in = fmemopen(buffer, length, "r");
if (in== NULL){
handle_error("fmemopen");}
// This is the part where I'm trying to feed my file as stdin
// since original fscanf expects stdin which I'm trying to hack
int dptr = fileno(in);
dup2(dptr, 0);
va_list args;
va_start(args, format);
int p = vfscanf(in, format, args);
va_end(ap);
fclose(in);
return p;
}
However, I'm getting Bad file descriptor
error. I would appreciate if someone can tell me what am I doing wrong.
I'm not clear where you got the idea that you should try to replace the file descriptor for stdin like this. It can't work that way, because the whole point of fmemopen
is that there is no underlying file (and thus no file descriptor) behind it; it's merely an adaptation of an in-memory buffer to the stdio API.
Fortunately, I see no reason you need or want to remap file descriptors to do what you want. If you're intercepting fscanf
and re-calling vfscanf
with a different FILE*
argument, stdin
is not getting used, so any changes to it would have no effect.