22.6 File handling functions

ChangeFileExt

Declaration:
Function ChangeFileExt(const FileName, Extension: string): string;
Description:
ChangeFileExt changes the file extension in FileName to Extension. The extension Extension includes the starting . (dot). The previous extension of FileName are all characters after the last ., the . character included.

If FileName doesn’t have an extension, Extension is just appended.

Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExpandFileName (741)

DeleteFile

Declaration:
Function DeleteFile(Const FileName : String) : Boolean;
Description:
DeleteFile deletes file FileName from disk. The function returns True if the file was successfully removed, False otherwise.
Errors:
On error, False is returned.
See also:
FileCreate (746), FileExists (747)

Listing: sysutex/ex31.pp


Program Example31;

{ This program demonstrates the DeleteFile function }

Uses sysutils;

Var
  Line : String;
  F,I : Longint;

Begin
  F:=FileCreate('test.txt');
  Line:='Some string line.'#10;
  For I:=1 to 10 do
    FileWrite (F,Line[1],Length(Line));
  FileClose(F);
  DeleteFile('test.txt');
End.

DoDirSeparators

Declaration:
Procedure DoDirSeparators(Var FileName : String);
Description:
This function replaces all directory separators 'ánd '/' to the directory separator character for the current system.
Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743)

Listing: sysutex/ex32.pp


Program Example32;

{ This program demonstrates the DoDirSeparators function }
{$H+}

Uses sysutils;

Procedure Testit (F : String);

begin
  Writeln ('Before : ',F);
  DoDirSeparators (F);
  Writeln ('After  : ',F);
end;

Begin
  Testit (GetCurrentDir);
  Testit ('c:\pp\bin\win32');
  Testit ('/usr/lib/fpc');
  Testit ('\usr\lib\fpc');
End.

ExpandFileName

Declaration:
Function ExpandFileName(Const FileName : string): String;
Description:
ExpandFileName expands the filename to an absolute filename. It changes all directory separator characters to the one appropriate for the system first.
Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743), ExtractRelativePath (744)

Listing: sysutex/ex33.pp


Program Example33;

{ This program demonstrates the ExpandFileName function }

Uses sysutils;

Procedure Testit (F : String);

begin
  Writeln (F,' expands to : ',ExpandFileName(F));
end;

Begin
  Testit('ex33.pp');
  Testit(ParamStr(0));
  Testit('/pp/bin/win32/ppc386');
  Testit('\pp\bin\win32\ppc386');
  Testit('.');
End.

ExpandUNCFileName

Declaration:
Function ExpandUNCFileName(Const FileName : string): String;
Description:
ExpandUNCFileName runs ExpandFileName (741) on FileName and then attempts to replace the driveletter by the name of a shared disk.
Errors:
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743), ExtractRelativePath (744)

ExtractFileDir

Declaration:
Function ExtractFileDir(Const FileName : string): string;
Description:
ExtractFileDir returns only the directory part of FileName, not including a driveletter. The directory name has NO ending directory separator, in difference with ExtractFilePath (743).
Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743), ExtractRelativePath (744)

Listing: sysutex/ex34.pp


Program Example34;

{ This program demonstrates the ExtractFileName function }
{$H+}
Uses sysutils;

Procedure Testit(F : String);

begin
 Writeln ('FileName      : ',F);
 Writeln ('Has Name      : ',ExtractFileName(F));
 Writeln ('Has Path      : ',ExtractFilePath(F));
 Writeln ('Has Extension : ',ExtractFileExt(F));
 Writeln ('Has Directory : ',ExtractFileDir(F));
 Writeln ('Has Drive     : ',ExtractFileDrive(F));
end;

Begin
  Testit (Paramstr(0));
  Testit ('/usr/local/bin/mysqld');
  Testit ('c:\pp\bin\win32\ppc386.exe');
  Testit ('/pp/bin/win32/ppc386.exe');
End.

ExtractFileDrive

Declaration:
Function ExtractFileDrive(const FileName: string): string;
Description:
Extract
Errors:
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743), ExtractRelativePath (744)

For an example, see ExtractFileDir (742).

ExtractFileExt

Declaration:
Function ExtractFileExt(const FileName: string): string;
Description:
ExtractFileExt returns the extension (including the .(dot) character) of FileName.
Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743), ExtractRelativePath (744)

For an example, see ExtractFileDir (742).

ExtractFileName

Declaration:
Function ExtractFileName(const FileName: string): string;
Description:
ExtractFileName returns the filename part from FileName. The filename consists of all characters after the last directory separator character (’/’ or ’´
)  or drive letter.

The full filename can always be reconstucted by concatenating the result of ExtractFilePath (743) and ExtractFileName.

Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743),ExtractRelativePath (744)

For an example, see ExtractFileDir (742).

ExtractFilePath

Declaration:
Function ExtractFilePath(const FileName: string): string;
Description:
ExtractFilePath returns the path part (including driveletter) from FileName. The path consists of all characters before the last directory separator character (’/’ or ’´)  , including the directory separator itself. In case there is only a drive letter, that will be returned.

The full filename can always be reconstucted by concatenating the result of ExtractFilePath and ExtractFileName (743).

Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743), ExtractRelativePath (744)

For an example, see ExtractFileDir (742).

ExtractRelativePath

Declaration:
Function ExtractRelativePath(Const BaseName,DestNAme : String): String;
Description:
ExtractRelativePath constructs a relative path to go from BaseName to DestName. If DestName is on another drive (Not on Linux) then the whole Destname is returned.

Note: This function does not exist in the Delphi unit.

Errors:
None.
See also:
ExtractFileName (743), ExtractFilePath (743), ExtractFileDir (742), ExtractFileDrive (742), ExtractFileExt (743),

Listing: sysutex/ex35.pp


Program Example35;

{ This program demonstrates the ExtractRelativePath function }

Uses sysutils;

Procedure Testit (FromDir,ToDir : String);

begin
  Write ('From "',FromDir,'" to "',ToDir,'" via "');
  Writeln (ExtractRelativePath(FromDir,ToDir),'"');
end;

Begin
 Testit ('/pp/src/compiler','/pp/bin/win32/ppc386');
 Testit ('/pp/bin/win32/ppc386','/pp/src/compiler');
 Testit ('e:/pp/bin/win32/ppc386','d:/pp/src/compiler');
 Testit ('e:\pp\bin\win32\ppc386','d:\pp\src\compiler');
End.

FileAge

Declaration:
Function FileAge(Const FileName : String): Longint;
Description:
FileAge returns the last modification time of file FileName. The FileDate format can be transformed to TDateTime format with the FileDateToDateTime (724) function.
Errors:
In case of errors, -1 is returned.
See also:
FileDateToDateTime (724), FileExists (747), FileGetAttr (747)

Listing: sysutex/ex36.pp


Program Example36;

{ This program demonstrates the FileAge function }

Uses sysutils;

Var S : TDateTime;
    fa : Longint;
Begin
  fa:=FileAge('ex36.pp');
  If Fa<>-1 then
    begin
    S:=FileDateTodateTime(fa);
    Writeln ('I''m from ',DateTimeToStr(S))
    end;
End.

FileClose

Declaration:
Procedure FileClose(Handle : Longint);
Description:
FileClose closes the file handle Handle. After this call, attempting to read or write from the handle will result in an error.
Errors:
None.
See also:
FileCreate (746), FileWrite (753), FileOpen (749), FileRead (750), FileTruncate (752), FileSeek (751)

For an example, see FileCreate (746)

FileCreate

Declaration:
Function FileCreate(Const FileName : String) : Longint;
Description:
FileCreate creates a new file with name FileName on the disk and returns a file handle which can be used to read or write from the file with the FileRead (750) and FileWrite (753) functions.

If a file with name FileName already existed on the disk, it is overwritten.

Errors:
If an error occurs (e.g. disk full or non-existent path), the function returns -1.
See also:
FileClose (745), FileWrite (753), FileOpen (749), FileRead (750), FileTruncate (752), FileSeek (751)

Listing: sysutex/ex37.pp


Program Example37;

{ This program demonstrates the FileCreate function }

Uses sysutils;

Var I,J,F : Longint;

Begin
  F:=FileCreate ('test.dat');
  If F=-1 then
    Halt(1);
  For I:=0 to 100 do
    FileWrite(F,I,SizeOf(i));
  FileClose(f);
  F:=FileOpen ('test.dat',fmOpenRead);
  For I:=0 to 100 do
    begin
    FileRead (F,J,SizeOF(J));
    If J<>I then
      Writeln ('Mismatch at file position ',I)
    end;
  FileSeek(F,0,fsFromBeginning);
  Randomize;
  Repeat
    FileSeek(F,Random(100)*4,fsFromBeginning);
    FileRead (F,J,SizeOf(J));
    Writeln ('Random read : ',j);
  Until J>80;
  FileClose(F);
  F:=FileOpen('test.dat',fmOpenWrite);
  I:=50*SizeOf(Longint);
  If FileTruncate(F,I) then
    Writeln('SuccessFully truncated file to ',I,' bytes.');
  FileClose(F);
End.

FileExists

Declaration:
Function FileExists(Const FileName : String) : Boolean;
Description:
FileExists returns True if a file with name FileName exists on the disk, False otherwise.
Errors:
None.
See also:
FileAge (745), FileGetAttr (747), FileSetAttr (752)

Listing: sysutex/ex38.pp


Program Example38;

{ This program demonstrates the FileExists function }

Uses sysutils;

Begin
  If FileExists(ParamStr(0)) Then
    Writeln ('All is well, I seem to exist.');
End.

FileGetAttr

Declaration:
Function FileGetAttr(Const FileName : String) : Longint;
Description:
FileGetAttr returns the attribute settings of file FileName. The attribute is a OR-ed combination of the following constants:
faReadOnly
The file is read-only.
faHidden
The file is hidden. (On LINUX, this means that the filename starts with a dot)
faSysFile
The file is a system file (On LINUX, this means that the file is a character, block or FIFO file).
faVolumeId
Volume Label. Not possible under LINUX.
faDirectory
File is a directory.
faArchive
file is an archive. Not possible on LINUX.
Errors:
In case of error, -1 is returned.
See also:
FileSetAttr (752), FileAge (745), FileGetDate (749).

Listing: sysutex/ex40.pp


Program Example40;

{ This program demonstrates the FileGetAttr function }

Uses sysutils;

Procedure Testit (Name : String);

Var F : Longint;

Begin
  F:=FileGetAttr(Name);
  If F<>-1 then
    begin
    Writeln ('Testing : ',Name);
    If (F and faReadOnly)<>0 then
      Writeln ('File is ReadOnly');
    If (F and faHidden)<>0 then
      Writeln ('File is hidden');
    If (F and faSysFile)<>0 then
      Writeln ('File is a system file');
    If (F and faVolumeID)<>0 then
      Writeln ('File is a disk label');
    If (F and faArchive)<>0 then
      Writeln ('File is artchive file');
    If (F and faDirectory)<>0 then
      Writeln ('File is a directory');
    end
  else
   Writeln ('Error reading attribites of ',Name);
end;

begin
  testit ('ex40.pp');
  testit (ParamStr(0));
  testit ('.');
  testit ('/');
End.

FileGetDate

Declaration:
Function FileGetDate(Handle : Longint) : Longint;
Description:
FileGetdate returns the filetime of the opened file with filehandle Handle. It is the same as FileAge (745), with this difference that FileAge only needs the file name, while FilegetDate needs an open file handle.
Errors:
On error, -1 is returned.
See also:
FileAge (745)

Listing: sysutex/ex39.pp


Program Example39;

{ This program demonstrates the FileGetDate function }

Uses sysutils;

Var F,D : Longint;

Begin
  F:=FileCreate('test.dat');
  D:=FileGetDate(D);
  Writeln ('File crerated on ',DateTimeToStr(FileDateToDateTime(D)));
  FileClose(F);
  DeleteFile('test.dat');
End.

FileOpen

Declaration:
Function FileOpen(Const FileName : string; Mode : Integer) : Longint;
Description:
FileOpen opens a file with name FileName with mode Mode. Mode can be one of the following constants:
fmOpenRead
The file is opened for reading.
fmOpenWrite
The file is opened for writing.
fmOpenReadWrite
The file is opened for reading and writing.

If the file has been successfully opened, it can be read from or written to (depending on the Mode parameter) with the FileRead (750) and FileWrite functions.

Remark that you cannot open a file if it doesn’t exist yet, i.e. it will not be created for you. If you want tp create a new file, or overwrite an old one, use the FileCreate (746) function.

Errors:
On Error, -1 is returned.
See also:
FileClose (745), FileWrite (753), FileCreate (746), FileRead (750), FileTruncate (752), FileSeek (751)

For an example, see FileOpen (749)

FileRead

Declaration:
Function FileRead(Handle : Longint; Var Buffer; Count : longint) : Longint;
Description:
FileRead reads Count bytes from file-handle Handle and stores them into Buffer. Buffer must be at least Count bytes long. No checking on this is performed, so be careful not to overwrite any memory. Handle must be the result of a FileOpen (749) call.
Errors:
On error, -1 is returned.
See also:
FileClose (745), FileWrite (753), FileCreate (746), FileOpen (749), FileTruncate (752), FileSeek (751)

For an example, see FileCreate (746)

FileSearch

Declaration:
Function FileSearch(Const Name, DirList : String) : String;
Description:
FileSearch looks for the file Name in DirList, where dirlist is a list of directories, separated by semicolons or colons. It returns the full filename of the first match found.
Errors:
On error, an empty string is returned.
See also:
ExpandFileName (741), FindFirst (753)

Listing: sysutex/ex41.pp


Program Example41;

{ Program to demonstrate the FileSearch function. }

Uses Sysutils;

Const
{$ifdef unix}
  FN = 'find';
  P = '.:/bin:/usr/bin';
{$else}
  FN = 'find.exe';
  P = 'c:\dos;c:\windows;c:\windows\system;c:\windows\system32';
{$endif}

begin
  Writeln ('find is in : ',FileSearch (FN,P));
end.

FileSeek

Declaration:
Function FileSeek(Handle,Offset,Origin : Longint) : Longint;
Description:
FileSeek sets the file pointer on position Offset, starting from Origin. Origin can be one of the following values:
fsFromBeginning
Offset is relative to the first byte of the file. This position is zero-based. i.e. the first byte is at offset 0.
fsFromCurrent
Offset is relative to the current position.
fsFromEnd
Offset is relative to the end of the file. This means that Offset can only be zero or negative in this case.

If successfull, the function returns the new file position, relative to the beginning of the file.

Remark: The abovementioned constants do not exist in Delphi.

Errors:
On error, -1 is returned.
See also:
FileClose (745), FileWrite (753), FileCreate (746), FileOpen (749) FileRead (750), FileTruncate (752)

Listing: sysutex/ex42.pp


Program Example42;

{ This program demonstrates the FileSetAttr function }

Uses sysutils;

Begin
  If FileSetAttr ('ex40.pp',faReadOnly or faHidden)=0 then
    Writeln ('Successfully made file hidden and read-only.')
  else
    Writeln ('Coulnd''t make file hidden and read-only.');
End.

For an example, see FileCreate (746)

FileSetAttr (Not on Linux)

Declaration:
Function FileSetAttr(Const Filename : String; Attr: longint) : Longint;
Description:
FileSetAttr sets the attributes of FileName to Attr. If the function was successful, 0 is returned, -1 otherwise.

Attr can be set to an OR-ed combination of the pre-defined faXXX constants.

Errors:
On error, -1 is returned (always on linux).
See also:
FileGetAttr (747), FileGetDate (749), FileSetDate (752).

FileSetDate (Not on Linux)

Declaration:
Function FileSetDate(Handle,Age : Longint) : Longint;
Description:
FileSetDate sets the file date of the file with handle Handle to Age, where Age is a DOS date-and-time stamp value.

The function returns zero of successfull.

Errors:
On Linux, -1 is always returned, since this is impossible to implement. On Windows and DOS, a negative error code is returned.
See also:

FileTruncate

Declaration:
Function FileTruncate(Handle,Size: Longint) : boolean;
Description:
FileTruncate truncates the file with handle Handle to Size bytes. The file must have been opened for writing prior to this call. The function returns True is successful, False otherwise.
Errors:
On error, the function returns False.
See also:
FileClose (745), FileWrite (753), FileCreate (746), FileOpen (749) FileRead (750), FileSeek (751)

For an example, see FileCreate (746).

FileWrite

Declaration:
Function FileWrite(Handle : Longint; Var Buffer; Count : Longint) : Longint;
Description:
FileWrite writes Count bytes from Buffer to the file with handle Handle. Prior to this call, the file must have been opened for writing. Buffer must be at least Count bytes large, or a memory access error may occur.

The function returns the number of bytes written, or -1 in case of an error.

Errors:
In case of error, -1 is returned.
See also:
FileClose (745), FileCreate (746), FileOpen (749) FileRead (750), FileTruncate (752), FileSeek (751)

For an example, see FileCreate (746).

FindClose

Declaration:
Procedure FindClose(Var F : TSearchrec);
Description:
FindClose ends a series of FindFirst (753)/FindNext (754) calls, and frees any memory used by these calls. It is absolutely necessary to do this call, or huge memory losses may occur.
Errors:
None.
See also:
FindFirst (753), FindNext (754).

For an example, see FindFirst (753).

FindFirst

Declaration:
Function FindFirst(Const Path : String; Attr : Longint; Var Rslt : TSearchRec) : Longint;
Description:
FindFirst looks for files that match the name (possibly with wildcards) in Path and attributes Attr. It then fills up the Rslt record with data gathered about the file. It returns 0 if a file matching the specified criteria is found, a nonzero value (-1 on linux) otherwise.

The Rslt record can be fed to subsequent calls to FindNext, in order to find other files matching the specifications.

remark: A FindFirst call must always be followed by a FindClose (753) call with the same Rslt record. Failure to do so will result in memory loss.

Errors:
On error the function returns -1 on linux, a nonzero error code on Windows.
See also:
FindClose (86)FindCloseSys, FindNext (754).

Listing: sysutex/ex43.pp


Program Example43;

{ This program demonstrates the FindFirst function }

Uses SysUtils;

Var Info : TSearchRec;
    Count : Longint;

Begin
  Count:=0;
  If FindFirst ('/*',faAnyFile and faDirectory,Info)=0 then
    begin
    Repeat
      Inc(Count);
      With Info do
        begin
        If (Attr and faDirectory) = faDirectory then
          Write('Dir : ');
        Writeln (Name:40,Size:15);
        end;
    Until FindNext(info)<>0;
    end;
  FindClose(Info);
  Writeln ('Finished search. Found ',Count,' matches');

End.

FindNext

Declaration:
Function FindNext(Var Rslt : TSearchRec) : Longint;
Description:
FindNext finds a next occurrence of a search sequence initiated by FindFirst. If another record matching the criteria in Rslt is found, 0 is returned, a nonzero constant is returned otherwise.

remark: The last FindNext call must always be followed by a FindClose call with the same Rslt record. Failure to do so will result in memory loss.

Errors:
On error (no more file is found), a nonzero constant is returned.
See also:
FindFirst (753), FindClose (86)

For an example, see FindFirst (753)

GetDirs

Declaration:
Function GetDirs(Var DirName : String; Var Dirs : Array of pchar) : Longint;
Description:
GetDirs splits DirName in a null-byte separated list of directory names, Dirs is an array of PChars, pointing to these directory names. The function returns the number of directories found, or -1 if none were found. DirName must contain only OSDirSeparator as Directory separator chars.
Errors:
None.
See also:
ExtractRelativePath (744)

Listing: sysutex/ex45.pp


Program Example45;

{ This program demonstrates the GetDirs function }
{$H+}

Uses sysutils;

Var Dirs : Array[0..127] of pchar;
    I,Count : longint;
    Dir,NewDir : String;

Begin
  Dir:=GetCurrentDir;
  Writeln ('Dir : ',Dir);
  NewDir:='';
  count:=GetDirs(Dir,Dirs);
  For I:=0 to Count-1 do
    begin
    NewDir:=NewDir+'/'+StrPas(Dirs[I]);
    Writeln (NewDir);
    end;
End.

RenameFile

Declaration:
Function RenameFile(Const OldName, NewName : String) : Boolean;
Description:
RenameFile renames a file from OldName to NewName. The function returns True if successful, False otherwise.

Remark: you cannot rename across disks or partitions.

Errors:
On Error, False is returned.
See also:
DeleteFile (739)

Listing: sysutex/ex44.pp


Program Example44;

{ This program demonstrates the RenameFile function }

Uses sysutils;

Var F : Longint;
    S : String;

Begin
  S:='Some short file.';
  F:=FileCreate ('test.dap');
  FileWrite(F,S[1],Length(S));
  FileClose(F);
  If RenameFile ('test.dap','test.dat') then
    Writeln ('Successfully renamed files.');
End.

SetDirSeparators

Declaration:
Function SetDirSeparators(Const FileName : String) : String;
Description:
SetDirSeparators returns FileName with all possible DirSeparators replaced by OSDirSeparator.
Errors:
None.
See also:
ExpandFileName (741), ExtractFilePath (743), ExtractFileDir (742)

Listing: sysutex/ex47.pp


Program Example47;

{ This program demonstrates the SetDirSeparators function }

Uses sysutils;

Begin
  Writeln (SetDirSeparators('/pp\bin/win32\ppc386'));
End.