gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:10:20 24 4
gpt4 key购买 nike

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

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_filebuf 不会在 FILE* 被销毁时关闭它,因此请记住在需要时自行关闭。

关于c++ - 无法使用 __gnu_cxx::stdio_filebuf 进行流式传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22213624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com