Jumat, 28 Desember 2007

File I/O - Delphi Examples

File I/O - Delphi Examples
There are 3 basic methods to perform File I/O
Use Pascal file variables
Use Windows API function wrappers
Use Windows API functions
The delphi help files suggest that you use the Pascal routines if you can.
Use of the non-native Pascal file variable handlers such as FileOpen is discouraged. These routines map to the Windows API functions and return file handles, not normal Pascal file variables. These are low-level file access routines. For normal file operations use the normal AssignFile, Rewrite, Reset operations instead of FileOpen.
(From the Delphi FileOpen help.)

File Manager Commands
File I/O Commands
File Search Commands
Testing for the Existance of a File
Testing for the Existance of a Directory
Opening and Reading a File
File Manager Commands
SysUtils/FileOpen and System/AssignFile have different commands for many of these

See SysUtils / File-management routines and System / I/O routines
Change Directory SetCurrentDir('c:\path')
Make Directory CreateDir('c:\path')
ForceDirectories('c:\path1\path2')
Remove Directory RemoveDir('c:\path')
RmDir(str)
Change Drive (no known function)
Rename a File RenameFile('test.txt', 'string.tst')
ChangeFileExt('test.txt', 'doc')
Delete a File DeleteFile('c:\*.tst') - Don't know if wildcards are allowed
Search for File t_str := FileSearch('readme.txt', 'c:\;c:\windows');
t_int := FindFirst ('c:\*.tst', attr, F) ;
Current Drirectory t_str := GetCurrentDir ;
Get File Attributes temp = FileGetAttr('c:\filename.tst')
Get File Mode TSearchRec.Attr (use with FindFirst or FindNext)
Set File Attributes FileSetAttr('c:\filename.tst', faReadOnly)
Get File Length TSearchRec.Size (use with FindFirst or FindNext)
FileSize(var F)
Get File Date/Time tempDate := FileGetDate(Handle) ;
Set File Date/Time FileSetDate(Handle, Age)
Test File existance if FileExists('c:\filename.tst') then
Test Directory existance if DirectoryExists('c:\temp') then


AdjustLinesBreaks(const S: string): string; - adjusts all line breaks in the string S to be true CR/LF

File I/O Commands
Open File for I/O FileOpen(const FileName: string; Mode: Integer): Integer;
AssignFile(F, OpenDialog1.FileName);
Rewrite(var F: File [; Recsize: Word ] );
Append(var F: Text);
Get File Mode F.Mode or (F as TFileRec).Mode
Write to File FileWrite(Handle: Integer; const Buffer; Count: Integer): Integer;
Write to TextFile Writeln, Write
Write to File BlockWrite()
Read From TextFile Read, Readln
Read From File BlockRead()
Set Current Location Seek(var F; N: Longint);
Get Current Location FilePos(var F)
Length of File FileSize(var F)
End of File while not Eof(F1) do
Close File FileClose(Handle: Integer)
CloseFile(F1);
Closes All Files Not available in Delphi


var
f1 : file;
f2 : text;
f3 : textfile; // from AssignFile hlp

(* File type declarations from Delphi file help *)
type
Person = record
FirstName: string[15];
LastName : string[25];
Address : string[35];
end;
PersonFile = file of Person;
NumberFile = file of Integer;
SwapFile = file;

TFileRec = record
Handle: Integer;
Mode: Integer;
RecSize: Cardinal;
Private: array[1..28] of Byte;
UserData: array[1..32] of Byte;
Name: array[0..259] of Char;
end;


File Search Commands
Files and directories may not have the same names. The more complicated FindFirst command must be used because FileExists does not find directories.
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle;
FindData: TWin32FindData;
end;

var
tempStr : string ;
FileFound : SmallInt ;
SearchRec : TSearchRec;
const
crlf = Chr(13) + Chr(10) ; // Carriage return & Linefeed
begin
FileFound := FindFirst('c:\temp', faAnyFile, SearchRec);
If FileFound = 0 then // a match was found
begin
If (SearchRec.Attr And faDirectory) <> 0 Then
tempStr := 'The following directory already exists.'
Else
tempStr := 'A file with the following name already exists.' ;
tempStr := tempStr + crlf + crlf + ' ' + 'c:\temp' ;
ShowMessage(tempStr)
end;
FindClose(SearchRec); // This is required to free memory
end;

Testing for the Existance of a File
The following is from the reset example.
function FileExists(FileName: string): Boolean;
{ Boolean function that returns True if the file exists; otherwise,
it returns False. Closes the file if it exists. }
var
F: file;
begin
{$I-}
AssignFile(F, FileName);
FileMode := 0; ( Set file access to read only }
Reset(F);
CloseFile(F);
{$I+}
FileExists := (IOResult = 0) and (FileName <> '');
end; { FileExists }
In Delphi 5, FileExists is built-in.

Testing for the Existance of a Directory

FileExists(tt) does not find directories. Can use stream objects which have handles

With Delphi 5, you can use
if DirectoryExists('c:\temp') then

Opening and Reading a File
The following is from the AssignFile example.
var
F: TextFile;
S: string;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(F, OpenDialog1.FileName); { File selected in dialog box }
Reset(F);
Readln(F, S); { Read the first line out of the file }
Edit1.Text := S; { Put string in a TEdit control }
CloseFile(F);
end;
end;
File copy - from the Eof, Read, Write example. To use this, create a form with a button, a Dialogs / OpenDialog component and a Dialogs / SaveDialog component. Double click the button (to open the source code) and paste the following code. Be sure that the code begins with var and not begin.
procedure TForm1.CopyFile();
var
F1, F2: TextFile;
Ch: Char;
begin
if OpenDialog1.Execute then begin
AssignFile(F1, OpenDialog1.Filename);
Reset(F1);
if SaveDialog1.Execute then begin
AssignFile(F2, SaveDialog1.Filename);
Rewrite(F2);
while not Eof(F1) do
begin
Read(F1, Ch);
Write(F2, Ch);
end;
CloseFile(F2);
end;
CloseFile(F1);

end;
end; // of procedure TForm1.CopyFile()

Author: Robert Clemenzi - clemenzi@cpcug.org
URL: http:// cpcug.org / user / clemenzi / technical / Languages / Delphi / DelphiFileIO.htm

source : http://mc-computing.com/languages/Delphi/DelphiFileIO.htm#Open

Label:

0 Komentar:

Posting Komentar

Berlangganan Posting Komentar [Atom]

<< Beranda