Delphi TFileStream.Seek, how to check for invalid

2019-07-19 21:57发布

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条回答
Explosion°爆炸
2楼-- · 2019-07-19 22:46

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

查看更多
Viruses.
3楼-- · 2019-07-19 22:55

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.

查看更多
登录 后发表回答