作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这会创建文件,但不会写入任何内容。
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/
这会创建文件,但不会写入任何内容。 std::ofstream outstream; FILE * outfile; outfile = fopen("/usr7/cs/test_file.txt",
我是一名优秀的程序员,十分优秀!