fmemopen, open_memstream, open_wmemstream

来源:互联网 发布:python 修改字符串 编辑:程序博客网 时间:2024/05/01 23:08

http://blog.csdn.net/sunboy_2050/article/details/6121069

http://blog.csdn.net/whinah/article/details/4310566

一直希望有个可以像 FILE* 一样使用的 memory file,正好,今天,在linux的stdio.h中找到了这个东西。

 

#define _GNU_SOURCE
#include <
stdio.h>

FILE *fmemopen(void *buf, size_t size, const char *mode);

FILE *open_memstream(char ** ptr, size_t *sizeloc) ;

#include <wchar.h>       FILE *open_wmemstream(wchar_t **ptr, size_t *sizeloc);

 

详细说明:http://linux.die.net/man/3/open_memstream

 

fmemopen 有用之处主要在于从内存中读取,使用 fscanf。当然也可以写,如果是为了写,并且随后再读,可以将 buf 和 size指定为 NULL,0,这样写时会自动增加内存。

 

open_memstream 就主要用于写了,比如生成sql语句:

 

[cpp] view plaincopy
  1. int i;  
  2. char* sql = NULL;  
  3. size_t len = 0;  
  4. FILE* mf = open_memstream(&sql, &len);  
  5. fprintf(mf, "insert into test(a,b,c) values");  
  6. for (i = 0; i < 100; ++i)  
  7.    fprintf(mf, "(%d,%d,%d),", i, i*i, i*i*i);  
  8. fclose(mf); // write a /0 at the end of sql, now len==strlen(sql)  
  9. sql[len-1] = 0; // trim last ','  
  10. execute(sql);  
  11. free(sql); // sql should be freed by the caller