TFile - Binary File I/O
Source: source/classes/tfile.prg
TFile provides low-level binary file input/output operations. It wraps the Harbour file-handling
APIs (FOpen(), FRead(), FWrite(), etc.) into an
object-oriented interface with sequential and random-access positioning, byte/word/string
read/write, searching, counting, and insertion/deletion of bytes. TFile is the base parent class
of TObjFile, TLibFile, and TTxtFile.
classDiagram
class TFile {
+cName
+hFile
+nLen
+nMode
+New(cFile, nMode)
+Create(cFile, nMode)
+nGetByte()
+nGetWord()
+cGetStr(n)
+PutByte(n)
+PutWord(n)
+PutStr(c)
+GoTop()
+GoBottom()
+Skip(n)
+GoTo(n)
+Seek(cStr)
+Count(cStr)
+DelBytes(n)
+InsBytes(n)
+lEof()
+lBoF()
+Close()
}
TFile <|-- TObjFile
TFile <|-- TLibFile
TFile <|-- TTxtFile
DATA Members
| DATA | Type | Description |
|---|---|---|
cName | Character | File name (full path) |
hFile | Numeric | Harbour file handle returned by FOpen()/FCreate() |
nLen | Numeric | File length in bytes |
nMode | Numeric | File open mode (0=read, 1=write, 2=read+write) |
Methods
| Method | Description |
|---|---|
New( cFile, nMode ) | Open an existing file. nMode: 0=read, 1=write, 2=read+write |
Create( cFile, nMode ) | Create a new file (or truncate existing). nMode: 1=write, 2=read+write |
nGetByte() | Read one byte (0-255) at current position and advance |
nGetWord() | Read two bytes as a signed 16-bit integer and advance |
cGetStr( n ) | Read n bytes as a character string and advance |
PutByte( n ) | Write one byte at current position and advance |
PutWord( n ) | Write two bytes (16-bit integer) at current position and advance |
PutStr( c ) | Write a character string at current position and advance |
GoTop() | Seek to beginning of file (position 0) |
GoBottom() | Seek to end of file |
Skip( n ) | Move forward (positive n) or backward (negative n) n bytes |
GoTo( n ) | Seek to absolute byte position n |
Seek( cStr ) | Search forward for string cStr, return position or 0 if not found |
Count( cStr ) | Count occurrences of string cStr in the file |
DelBytes( n ) | Delete n bytes at current position (shifts remainder left) |
InsBytes( n ) | Insert n zero-bytes at current position (shifts remainder right) |
lEof() | Return .T. if at end of file |
lBoF() | Return .T. if at beginning of file |
Close() | Close the file handle |
Example: Read a Binary File Byte by Byte
#include "FiveWin.ch"
function Main()
local oFile := TFile():New( "c:\data\sample.bin", 0 )
local nByte, aBytes := {}
if oFile:hFile != nil
while ! oFile:lEof()
nByte := oFile:nGetByte()
if nByte != -1
AAdd( aBytes, nByte )
endif
endwhile
oFile:Close()
? "Total bytes read:", Len( aBytes )
? "First byte:", aBytes[ 1 ]
? "Last byte:", aBytes[ Len( aBytes ) ]
else
? "Cannot open file"
endif
return nil