[fpc-pascal] Adding file to string to the RTL
Michael Van Canneyt
michael at freepascal.org
Tue Oct 6 10:12:04 CEST 2020
On Mon, 5 Oct 2020, Ryan Joseph via fpc-pascal wrote:
>
>
>> On Oct 5, 2020, at 5:08 PM, Jean SUZINEAU via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>> In my own code I use BlockRead/BlockWrite, but I'm wondering if I've not seen this somewhere in RTL.
>>
>>
>
> This looks good to me what about the concerns raised by Michael? I don't
> know enough about text formats but using AnsiString always just seems to
> work for me (I assume the compiler did something magic behind the scenes).
No, we don't deal in magic, only bits and bytes :-)
I added the following functions to the sysutils unit (rev 47056):
// Read raw content as bytes
Function GetFileContents(Const aFileName : RawByteString) : TBytes;
Function GetFileContents(Const aFileName : UnicodeString) : TBytes;
Function GetFileContents(Const aHandle : THandle) : TBytes;
// Read content as string
// Assume TEncoding.SystemEncoding
Function GetFileAsString(Const aFileName : RawByteString) : RawByteString;
// Specify encoding
Function GetFileAsString(Const aFileName : RawByteString; aEncoding : TEncoding) : RawByteString;
// Assume TEncoding.Unicode contents
Function GetFileAsString(Const aFileName : UnicodeString) : UnicodeString;
// Specify encoding, return Unicode string.
Function GetFileAsString(Const aFileName : UnicodeString; aEncoding : TEncoding) : UnicodeString;
These functions will raise an exception if the file cannot be opened or read.
They cannot be used on handles that do not support FileSeek() (sockets, pipes, stdin/stdout etc.).
I did some tests on encoding conversion but not extensively.
If you find any errors, please report them through the bugtracker.
Michael.
More information about the fpc-pascal
mailing list