5

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.

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

ATemp
  • 319
  • 3
  • 10
  • 2
    But if seek fails for *unrelated* reasons (as you said), then it still means the stream is not seekable, whatever the reason may be. – Nawaz Feb 26 '12 at 06:19

1 Answers1

8

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++.

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.

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

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • I asked a question [here](https://stackoverflow.com/questions/32013906/use-seekoff-to-detect-a-fire-hose-istream), which was proposed as a duplicate of this one, that asked whether "attempting to do so" would even work. If it does, at least it's a way. – Spencer Jan 04 '22 at 20:45