分享

memory FILE in C

 心不留意外尘 2016-05-23
     作者: 发表日期: 2009年06月30日 

http:///p/?p=77

一直希望有个可以像 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) ;

 

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

 

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

 

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

 

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多