无法使用__gnu_cxx::stdio_filebuf进行流式传输

Not able to ofstream using __gnu_cxx::stdio_filebuf

本文关键字:传输 filebuf stdio gnu cxx      更新时间:2023-10-16

这会创建文件,但它不会写入任何内容。

std::ofstream outstream;
FILE * outfile;
outfile = fopen("/usr7/cs/test_file.txt", "w");
__gnu_cxx::stdio_filebuf<char> filebuf(outfile, std::ios::out);
outstream.std::ios::rdbuf(&filebuf);
outstream << "some data";
outstream.close();
fclose(outfile);

我知道还有其他简单的解决方案可以实现输出,但我需要使用这个非标准的 filebuf 在编辑时锁定文件,以便其他进程无法打开文件。我不知道为什么这不起作用。

std::ostream已经有一个构造函数在做正确的事情:

#include <ext/stdio_filebuf.h>
#include <iostream>
#include <fcntl.h>
int main() {
    auto file = fopen("test.txt", "w");
    __gnu_cxx::stdio_filebuf<char> sourcebuf(file, std::ios::out);
    std::ostream out(&sourcebuf);
    out << "Writing to fd " << sourcebuf.fd() << std::endl;
}

请记住,stdio_filebufFILE*被销毁时不会关闭它,所以如果需要,请记住自己做。