Components All New MacOS Windows Linux iOS
Examples Mac & Win Server Client Guides Statistic FMM Blog Deprecated Old

BinaryFile.ReadText

Reads text from file.

Component Version macOS Windows Linux Server iOS SDK
BinaryFile 7.3 ✅ Yes ✅ Yes ✅ Yes ✅ Yes ✅ Yes
MBS( "BinaryFile.ReadText"; BinaryFileRef; ByteCount { ; Encoding } )   More

Parameters

Parameter Description Example Flags
BinaryFileRef The reference number for the open file. $FH
ByteCount The number of Bytes to read. 1000
Encoding The text encoding for result.
Default is native. This function can also handle UTF-16 as well as UTF-16LE and UTF-16BE for little/big endian byte order.
Possible encoding names: ANSI, ISO-8859-1, Latin1, Mac, Native, UTF-8, DOS, Hex, Base64 or Windows. More listed in the FAQ.
UTF8 Optional

Result

Returns OK or error.

Description

Reads text from file.
You have to decide which encoding to use (if not UTF8). We support a few encodings, but we can add more if you need something special. Some characters will be wrong if the encoding is not correct.
The read text may be shorter than requested if you hit end of file.

When passing UTF-16 as encoding, we can detect byte order if there is a Byte Order Mark.

See also Text.ReadTextFile and Text.ReadTextFromContainer.

Examples

Read some text:

Set Variable [ $fh ; Value: MBS( "BinaryFile.Open"; "/Users/cs/Desktop/test.txt" ) ]
Set Variable [ $len ; Value: MBS("BinaryFile.Length"; $fh) ]
Set Variable [ $text ; Value: MBS( "BinaryFile.ReadText"; $fh; $len; "UTF-8" ) ]
Set Field [ test::ContainerField ; $text ]
Set Variable [ $r ; Value: MBS( "BinaryFile.Close"; $fh) ]

PNG file check:

// returns 1 if file is most likely a PNG as it starts with right bytes.
// for a CF, path may be a parameter.
Let ( [
    path = "/Users/cs/Pictures/test.png";
    stream = MBS( "BinaryFile.Open"; path );
    text = MBS( "BinaryFile.ReadText"; stream; 10; "Windows" );
    r = MBS( "BinaryFile.Close"; stream;);
    IsPNG = (Position ( text; "PNG"; 1; 1 ) = 2)
]; IsPNG )

PDF file check:

// returns 1 if file is most likely a PDF as it starts with right bytes.
// for a CF, path may be a parameter.
Let ( [
path = "/Users/cs/Pictures/test.png";
stream = MBS( "BinaryFile.Open"; path );
text = MBS( "BinaryFile.ReadText"; stream; 4; "Windows" );
r = MBS( "BinaryFile.Close"; stream;);
IsPDF = (text == "%PDF")
]; IsPDF )

See also

Blog Entries

This function checks for a license.

Created 12nd June 2017, last changed 1st June 2023


BinaryFile.ReadPDF - BinaryFile.Seek