views:

119

answers:

2

I am working with TFileStream in Delphi 2006. When I invoke TFileStream.Seek with an offset that is out of bounds I am getting different return values. When I seek to a position below the beginning of the stream, the function returns -1 and if I seek to a beyond the stream size, the function returns what would have been the position in the stream if the stream was that large. Is there a way to check whether a seek operation on the stream was successful? Why does TFileStream.Seek not fail when the seek offsets are out of bounds of the current stream size?

Thanks in advance.

+2  A: 

Yes, you can seek beyond file size - where is no error here, the seek is successful. More than that, you can lock file region (see LockFile) beyond file size - that is also OK and is used by some RDBMS to implement table/record locking.

Also from MSDN:

It is not an error to set a file pointer to a position beyond the end of the file. The size of the file does not increase until you call the SetEndOfFile, WriteFile, or WriteFileEx function. A write operation increases the size of the file to the file pointer position plus the size of the buffer written, which results in the intervening bytes uninitialized.

So by setting a file pointer beyond the file size you can subsequently increase the file size (ex by the SetEndOfFile).

Serg
This is exactly how `TFileStream`'s setter for the `Size` property is implemented - a seek to the specified size offset followed by a call to `SetEndOfFile()`.
Remy Lebeau - TeamB
A: 

It calls a windows function and the result you get is from the windows function.

I would be inclined to check in your code if the Seek value is valid. If you need to do this alot then maybe create a descendant of TFileStream, something like TRangeCheckingFileStream which includes range checks in it's seek method and returns a value you can expect.

JamesB