【问题标题】:Not able to ofstream using __gnu_cxx::stdio_filebuf无法使用 __gnu_cxx::stdio_filebuf 进行流式传输
【发布时间】:2014-03-06 02:24:21
【问题描述】:

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

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 在编辑时锁定文件,以便其他进程无法打开文件。 我不知道为什么这不起作用。

【问题讨论】:

  • 你试过打开outstream吗?
  • 我认为你应该创建一个std::ostream 并从缓冲区构造它,就像在std::ostream outstream(&amp;filebuf) 中一样,所以你不必无缘无故地调用open()/close()。如果你这样做,你还需要outstream.std::ios::rdbuf(&amp;filebuf);
  • 很抱歉没有描述使用这个_gnu非标准filebuf的原因。我知道其他简单的解决方案可以产生输出,但我正在使用这种方法在编辑时锁定文件;使其他进程无法打开文本文件。
  • 你为什么不在这里使用std::ostream?如果std::ofstream 未打开,则尝试写入任何内容都将不起作用。

标签: c++ ostream filebuf


【解决方案1】:

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*,所以如果需要的话记得自己做。

【讨论】:

猜你喜欢
  • 2022-01-16
  • 2014-05-09
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 2017-05-26
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多