C ++如何检查流(iostream)是否可搜索 [英] C++ how to check if a stream (iostream) is seekable

查看:41
本文介绍了C ++如何检查流(iostream)是否可搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查ostream的istream是否可搜索?

Is there a way I can check if an istream of ostream is seekable?

我怀疑正在执行测试搜索并检查故障位不正确因为搜索可能会由于不相关的原因而失败.

I suspect doing a test seek and checking for failbit is not correct since the seek can fail for unrelated reasons.

我需要它在 Linux 和 mac 上工作,如果这有区别的话.

I need this to work on Linux and mac, if that makes a difference.

推荐答案

Iostream不会给您带来太多好处.流对象只是包装来自类 std :: streambuf 的缓冲区对象的包装.(假定为窄"字符.)标准的派生缓冲区类是 std :: stringbuf (用于字符串)和 std :: filebuf (用于文件).假设您只对文件感兴趣, std :: filebuf 只是围绕C库功能的简单包装.C库没有定义确定 FILE 对象是否支持查找的方法,除了尝试这样做之外,C ++也没有.

Iostreams doesn't give you much. Stream objects are just wrappers around a buffer object derived from class std::streambuf. (Assuming "narrow" characters.) The standard derived buffer classes are std::stringbuf for strings and std::filebuf for files. Supposing you're only interested in files, std::filebuf is just a simple wrapper around the C library functionality. The C library does not define a way to determine if a FILE object supports seeking or not, besides attempting to do so, so neither does C++.

就其价值而言, seek 的语义有所不同.某些平台可能允许您搜索"管道,但只能搜索当前位置,以确定已读取或写入了多少个字符.寻求结束可能会调整文件的大小,或者可能导致下一次写操作调整文件的大小,或者介于两者之间.

For what it's worth, the semantics of seek vary a bit. Some platforms might allow you to "seek" a pipe but only to the current position, to determine how many characters have been read or written. Seeking past the end might resize the file, or might cause the next write operation to resize the file, or something in between.

您还可以尝试检查是否设置了 badbit (或者,按照我的喜好,使用异常代替标志)来检查 errno .

You might also try checking errno if badbit is set (or, as I prefer, use exceptions instead of flags).

这篇关于C ++如何检查流(iostream)是否可搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆