尝试将 fmemopen 文件描述符与 stdin 相关联时出现错误的文件描述符错误

Bad file descriptor error when trying to associate fmemopen file descriptor with stdin

我正在尝试插入最初从 stdin 读取的 fscanf 函数,例如 fscanf(stdin,"%ms", &secret)。在我的插入函数中,我试图让它从我用字符串创建的输入文件中读取。以下是我正在做的事情:

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;
}

但是,我遇到 Bad file descriptor 错误。如果有人能告诉我我做错了什么,我将不胜感激。

我不清楚您是从哪里想到应该像这样尝试替换 stdin 的文件描述符的。它不能那样工作,因为 fmemopen 的全部意义在于它背后没有底层文件(因此没有文件描述符);它只是内存缓冲区对 stdio API.

的改编

幸运的是,我看不出您需要或想要重新映射文​​件描述符来执行您想要的操作。如果您拦截 fscanf 并使用不同的 FILE* 参数重新调用 vfscanf,则 stdin 不会被使用,因此对其进行的任何更改都将无效。

fmemopen(3) 写道:

NOTES

There is no file descriptor associated with the file stream returned by this function (i.e., fileno(3) will return an error if called on the returned stream).