easy way to determine if a stream or fd is seekable

Tim Kientzle tim at kientzle.com
Fri Nov 18 20:32:14 UTC 2011


On Nov 17, 2011, at 1:48 PM, Alexander Best wrote:

> On Thu Nov 17 11, Dieter BSD wrote:
>>> lseek() on a tape drive does not return an error, nor does it
>>> actually do anything.
>> 
>> IIRC some tape drives can seek, while others cannot.
>> Vague memories that it is supposed to be possible to put a
>> filesystem on a DECtape and mount the filesystem.
> 
> or how about the following:
> 
> 1) if the file argument we're seeking on is a tape drive, just do a regular
>   seek operation.
> 2) afterwards use ftell() to verify that the seek REALLY happend. if it didn't,
>   return -1 and set errno = EBADF.

ftell() can't tell whether the seek really happened or not.
All it can do is ask the kernel, and the kernel doesn't know.

Here is my current understanding:

When you call lseek(), the kernel just stores the requested
offset in the file descriptor.  lseek() always succeeds because
storing the requested offset in the file descriptor always succeeds.
(Except that the kernel specially checks if the file descriptor
is a pipe.)

ftell() just obtains the data from the file descriptor.
So it always succeeds and always returns the data from
the previous seek request, regardless of whether that seek
actually did anything.

With the next read or write request, the device driver may inspect the
offset information in the file descriptor.  Or it can ignore
it.  Almost all tape device drivers ignore it.  Filesystems
uniformly support it.  Disk drivers uniformly support it.
Other drivers vary considerably.

In short:  No, there is no "easy way" to determine if an
arbitrary stream or fd is seekable.  If you try to create
a function that determines this, be certain to include
"Don't Know" as a possible return value.

Tim



More information about the freebsd-hackers mailing list