c++ - 从写入 FILE* 的函数中获取数据

标签 c++ c file

<分区>

我有以下函数(来自 lionet asn1 编译器 API):

int xer_fprint(FILE *stream, struct asn_TYPE_descriptor_s *td, void *sptr);

第一个参数是 FILE*,这是输出的地方。

这个有效:

xer_fprint(stdout, &asn_struct, obj);

还有这个:

FILE* f = fopen("test.xml", "w");
xer_fprint(f, &asn_struct, obj);
fclose(f);

但我需要一个字符串中的数据(最好是 std::string)。

我该怎么做?

最佳答案

在 Linux 上,您有 fmemopen,它创建一个 FILE * 句柄到临时内存缓冲区:

char * buffer = malloc(buf_size);
FILE * bufp = fmemopen(buffer, buf_size, "wb");

如果这不可用,那么您可以尝试将 FILE * 附加到 POSIX 共享内存文件描述符:

int fd = shm_open("my_temp_name", O_RDWR | O_CREAT | O_EXCL, 0);
// unlink it
shm_unlink("my_temp_name");
// on Linux this is equivalent to
fd = open("/dev/shm/my_temp_name", O_RDWR | O_CREAT | O_EXCL); unlink("/dev/shm/my_temp_name");

FILE * shmp = fdopen(fd, "wb");

// use it

char * buffer = mmap(NULL, size_of_buf , PROT_READ, MAP_SHARED, fd, 0);

关于c++ - 从写入 FILE* 的函数中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24365274/

相关文章:

c++ - "position"是 C++ 中的保留字吗?

c++ - 如何遍历 CListCtrl 的元素?

c++ - 库中的 exit() 可以用抛出异常代替吗?

C 语义 : "col -= size--" having++ or -- operating in an expression

c++ - 如何使用 Qt/C++ 在 Windows 上将 GUI 转换为路径?

c++ - 调用析构函数方法比较

c - 为什么 Linux 内核使用它所使用的数据结构?

vb.net - 在 VB.NET 中写入文本文件的有效方法

python - 将python编解码器转换为文本

c++ - 使用 C/C++ 和 openssl 处理单个 AES-128-ECB block