21

オフストリームがディスク デバイスに書き込まれていることを確認したいと考えています。これを行う移植可能な方法 (POSIX システムで移植可能) は何ですか?

読み取り専用open追加モードでファイルを個別に取得してファイル記述子を取得し、それを呼び出すと、問題は解決しますか? このような:fsync

ofstream out(filename);
/* ...
   write content into out
   ...
*/
out.close();

int fd = open(filename, O_APPEND);
fsync(fd);
close(fd);
4

4 に答える 4

10

Boost を使用できる場合は、file_descriptor_sink ベースのストリームを試してください。

boost::filesystem::path filePath("some-file");
boost::iostreams::stream<boost::iostreams::file_descriptor_sink> file(filePath);

//  Write some stuff to file.

//  Ensure the buffer's written to the OS ...
file.flush();

//  Tell the OS to sync it with the real device.
//
::fdatasync(file->handle());
于 2014-05-23T10:11:04.387 に答える
3

std::filebufおそらくその内部のどこかにファイル記述子がありますが、それを取得するには、実装固有の恐ろしいハックが必要です。

これは、libstdc++ に対する恐ろしいハックの 1 つです。

#include <fstream>
#include <unistd.h>

int GetFileDescriptor(std::filebuf& filebuf)
{
  class my_filebuf : public std::filebuf
  {
  public:
    int handle() { return _M_file.fd(); }
  };

  return static_cast<my_filebuf&>(filebuf).handle();
}

int main()
{
  std::ofstream out("test");

  out << "Hello, world!";
  out.flush();

  fsync(GetFileDescriptor(*out.rdbuf()));
}
于 2015-02-10T18:25:36.050 に答える
2

fsync()読み取り用に開いているファイル記述子に対して移植可能にすることはまったくできません。Linux では、記述子が書き込みモードでない場合に EBADF を生成すると記載されていfsync()ます

于 2009-03-24T10:22:41.243 に答える