【发布时间】: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(&filebuf)中一样,所以你不必无缘无故地调用open()/close()。如果你这样做,你还需要outstream.std::ios::rdbuf(&filebuf);。 -
很抱歉没有描述使用这个_gnu非标准filebuf的原因。我知道其他简单的解决方案可以产生输出,但我正在使用这种方法在编辑时锁定文件;使其他进程无法打开文本文件。
-
你为什么不在这里使用
std::ostream?如果std::ofstream未打开,则尝试写入任何内容都将不起作用。