【问题标题】:Get data from a function that writes to FILE* [duplicate]从写入 FILE* 的函数中获取数据 [重复]
【发布时间】:2014-06-23 11:54:54
【问题描述】:

我有以下函数(来自 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)。

我该怎么做?

【问题讨论】:

    标签: c++ c file


    【解决方案1】:

    在 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);
    

    【讨论】:

      【解决方案2】:

      在 C 中:打开文件并将其读回。使用合适的临时文件位置。没有标准方法可以创建 FILE * 的内存(“字符串流”)版本。

      【讨论】:

        【解决方案3】:

        GNU 的libc 提供string streams 作为标准库的扩展。

        fmemopenopen_memstream 函数允许您对字符串或内存缓冲区执行 I/O。这些设施在stdio.h 中声明。

        【讨论】:

          【解决方案4】:

          据我了解,您想调用 xer_fprint 来写入内存缓冲区。我认为没有直接的方法可以做到这一点,但我认为你可以使用管道。下面应该给你一些尝试的想法:

          int rw[2]; 
          int ret = pipe(rw);
          FILE* wrFile = fdopen(rd[1], 'w'); 
          xer_fprint(wrFile, &asn_struct, obj); 
          
          // ...  later/in another thread 
          namespace io = boost::iostreams; 
          io::stream_buffer<io::file_descriptor_source> fpstream (rw[0]);
          std::istream in (&fpstream);
          std::string data; 
          in >> data; 
          

          【讨论】:

            猜你喜欢
            • 2013-03-16
            • 2022-01-07
            • 2014-07-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多