Creating a FILE * stream that results in a string

后端 未结 3 1318
星月不相逢
星月不相逢 2020-12-06 13:40

I\'m looking for a way to pass in a FILE * to some function so that the function can write to it with fprintf. This is easy if I want the output t

3条回答
  •  庸人自扰
    2020-12-06 14:22

    I'm not sure I understand why you want to mess up with FILE *. Couldn't you simply write to a file and then load it in string?

     char *get_file_in_buf(char *filename) {
       char *buffer;
       ... get file size with fseek or fstat ...
       ... allocate buffer ...
       ... read buffer from file ...
       return buffer;
     }
    

    If you only want to "write" formatted text into a string, another option could be to handle an extensible buffer using snprintf() (see the answers to this SO question for a suggestion on how to handle this: Resuming [vf]?nprintf after reaching the limit).

    If, instead, you want to create a type that can be passed transparently to any function taking a FILE * to make them act on string buffers, it's a much more complex matter ...

提交回复
热议问题