Delphi TFileStream.Seek, how to check for invalid seek offset

匆匆过客 提交于 2019-12-24 04:55:14

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3300938/delphi-tfilestream-seek-how-to-check-for-invalid-seek-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!