Advanced Programming in UNIX Environment Episode 25
发布时间:2020-12-15 19:59:17 所属栏目:安全 来源:网络整理
导读:内存流 #include stdio.h FILE *fmemopen( void * restrict buf,size_t size, const char * restrict type); type参数控制如何使用流。 type 说明 r或rb 为读而打开 w或wb 为写而打开 a或ab 追加:为在第一个null字节处写而打开 r+或r+b或rb+ 为读和写而打开
内存流 #include <stdio.h>
FILE *fmemopen(void *restrict buf,size_t size,const char *restrict type);
type参数控制如何使用流。
#include "apue.h"
#define BSZ 48
int main()
{
FILE *fp;
char buf[BSZ];
memset(buf,'a',BSZ-2);
buf[BSZ-2]=' ';
buf[BSZ-1]='X';
if((fp=fmemopen(buf,BSZ,"w+"))==NULL)
err_sys("fmemopen failed");
printf("initial buffer contents: %sn",buf);
fprintf(fp,"hello,world");
printf("before flush: %sn",buf);
fflush(fp);
printf("after fflush: %sn",buf);
printf("len of string in buf = %ldn",(long)strlen(buf));
memset(buf,'b',BSZ-2);
buf[BSZ-2]=' ';
buf[BSZ-1]='X';
fprintf(fp,world");
fseek(fp,0,SEEK_SET);
printf("after fseek: %sn",buf);
printf("len of string int buf = %ldn",'c',world");
fclose(fp);
printf("after fclose: %sn",(long)strlen(buf));
return 0;
}
观察内存流的写入操作 书上说Linux支持,但是其他不支持。目前Mac 10.13也支持。 #include <stdio.h>
FILE *open_memstream( char **bufp,size_t *sizep);
#include <wchar.h>
FILE *open_wmemstream(wchar_t **bufp,size_t sizep);
这两个函数与fmemopen函数的不同在于:
原则: 标准I/O替代软件 标准I/O库的一个不足之处就是效率不高,这与他需要复制的数据量有关。一次是在内核和标准I/O缓冲区之间(当调用read和write时),第二次是在标准I/O缓冲区和用户程序中的行缓冲之间。 有快速I/O、sfio、ASI(Alloc Stream Interface)。 许多标准I/O库实现在C函数库中可用,这种C函数库是为内存较小的系统,如嵌入式系统设计的。uClibc C库和Newlib C库。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |