我正在尝试使用std :: iostream接口更新随机访问二进制文件,并通过seekg / seekp管理单独的get / put位置。使用stringstream一切正常,但是当我使用Boost.Iostream(特别是boost :: iostreams :: stream< boost :: iostreams :: file_descriptor>)创建基于文件描述符的流时,获取/放置头寸不再是独立的。
我从Modes的文档中收集到,我正在寻找的是“双向可搜索”流。文档显示Mode是stream的模板参数,“主要供内部使用”,但这似乎(不再?)正确。相反,模式(又名类别?)直接来自设备:
template< typename Device,
typename Tr = ...,
typename Alloc = ...>
struct stream : detail::stream_base<Device, Tr, Alloc> {
public:
typedef typename char_type_of<Device>::type char_type;
struct category
: mode_of<Device>::type,
closable_tag,
detail::stream_traits<Device, Tr>::stream_tag
{ };
主要问题:是否有某种方法可以从设备获取双重搜索行为,例如file_descriptor(标记为可搜索但不是可搜索的)?
次要问题:对于seekg / seekp的独立性是否有任何一般保证?我从网络搜索中收集到stringstream似乎是独立的,但是fstream可能不是。但是,我找不到任何权威的东西。
答案 0 :(得分:1)
如果构建bidirectional_seekable boost::iostreams::device
,它将支持两个单独的get / put位置,可以在iostreams::seek
函数的帮助下修改它们。
粗略地说,这看起来像是:
struct binary_seekable_device
: boost::iostreams::device<boost::iostreams::bidirectional_seekable>
{
explicit binary_seekable_device(int fd)
: fd(fd), pos_read(0), pos_write(0) {}
std::streamsize read(char *s, std::streamsize n);
std::streamsize write(char const *s, std::streamsize n);
std::streampos seek(boost::iostreams::stream_offset off,
std::ios::seekdir way, std::ios::openmode which);
int fd;
std::size_t pos_read;
std::size_t pos_write;
};
您需要通过填写三个函数(读取,写入,搜索)来实现流逻辑,有关详细信息,请参阅示例和文档。对您而言重要的是参数std::ios::openmode which
,为您提供了更新所需位置(读取,写入或两者)的线索。
现在在实例化boost :: iostreams :: stream时使用此设备:
int fd = open(...);
boost::iostream::stream<binary_seekable_device> s(fd);
其中s是您可以用来执行require文件操作的流实例。