【linux编程】函数fmemopen、函数open_memstream

函数fmemopen、函数open_memstream

1. open_memstream函数原型:

#include <stdio.h>
FILE *open_memstream(char **ptr, size_t *sizeloc);

2. fmemopen函数原型:

#include <stdio.h>
FILE *fmemopen(void buf[.size], size_t size, const char *mode);

1. 例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char *write_to_buf(char *msg)
{
    char *buf = (char *)malloc(1024);
 
    FILE *fp = fmemopen(buf, 1024, "w");
    fwrite(msg, 1, strlen(msg), fp);
    fclose(fp);
    return buf;
}
 
int main(void)
{
	char *str = "hello, world!";
	char *buf = write_to_buf(str);
 
	printf("%s\n", buf);
	free(buf);
	return 0;
}

2. 例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char *write_to_buf(char *msg)
{
	char *buf = NULL;
	size_t size = 0;
 
	FILE *fp = open_memstream(&buf, &size);
	fwrite(msg, 1, strlen(msg), fp);
	fclose(fp);
	return buf;
}
 
int main(void)
{
	char *str = "hello, world!";
	char *buf = write_to_buf(str);
 
	printf("%s\n", buf);
 
	free(buf);
	return 0;
}

 

posted @ 2023-06-27 14:17  苏格拉底的落泪  阅读(173)  评论(0编辑  收藏  举报