4

これによりファイルが作成されますが、何も書き込まれません。

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 を使用して編集中にファイルをロックし、他のプロセスがファイルを開くことができないようにする必要があります。なぜこれが機能しないのかわかりません。

4

1 に答える 1

2

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*ことに注意してください。必要な場合は自分で行うことを忘れないでください。

于 2015-05-15T15:54:37.493 に答える