Delphi中用於讀寫(I/O)的三種檔案類型
一.舊pascal文件類型
用舊檔案變數表示的檔案類型,例如F:text,F:File. 定義了三類:有類型,無類型,字元類型以及一些Delphi的檔案操作函數.例如:AssignPRn,Writeln,這些檔案類別和Windows文件句柄不相容
二.Windows檔案句柄(handle)
物件導向的Pascal的檔案句柄封裝了Windows檔案句柄類型,檔案操作函式庫則封裝了Windows API函數,例如"Fileread"就是呼叫了Windows API 函式"ReadFile",Delphi提供了一個Windows API操作介面如果熟悉Windows API,可以用Windows檔案句進行檔案操作.
三.檔案流(File Streams)
文件流是TFileStream類別的物件實例,文件流是高層的文件操作類型,TFileStream提供了一個句柄屬性.用此屬性可操作Windows文件句柄類型.
如何選擇文件類型
Windows檔案句柄是較底層的檔案操作類型,提供了靈活的同步及非同步檔案讀寫控制,以下提供用Windows檔案句柄類型對檔案同步及非同步操作的偽代碼描述:
同步操作:
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL) ;
// check for eof
if (bResult && nBytesRead == 0, ) {
// we're at the end of the file
}
非同步操作:
// set up overlapped structure fields
gOverLapped.Offset = 0;
gOverLapped.OffsetHigh = 0;
gOverLapped.hEvent = NULL;
// attempt an asynchronous read Operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead,
&gOverlapped) ;
// if there was a problem, or the async. operation's still pending ...
if (!bResult)
{
// deal with the error code
switch (dwError = GetLastError())
{
case ERROR_HANDLE_EOF:
{
// we're reached the end of the file
// during the call to ReadFile
// code to handle that
}
case ERROR_IO_PENDING:
{
// asynchronous i/o is still in progress
// do something else for a while
GoDoSomethingElse() ;
// check on the results of the asynchronous read
bResult = GetOverlappedResult(hFile, &gOverlapped,
&nBytesRead, FALSE) ;
// if there was a problem ...
if (!bResult)
{
// deal with the error code
switch (dwError = GetLastError())
{
case ERROR_HANDLE_EOF:
{
// we're reached the end of the file
file during asynchronous operation
}
// deal with other error cases
}
}
} // end case
// deal with other error cases
} // end switch
} // end if
雖然Windows文件句柄提供靈活的文件控制,但須編寫更多的出錯處理代碼,如果對
WindowsAPI不熟悉,使用Delphi推薦的舊檔案變數類型.
Delphi的舊文件類型使用AssignFile,使文件變數和物理文件關聯,透過Delphi定義的
對檔案變數的各種操作,完成檔案的存取和操作.使用方便.以下提供對檔案變數類
型的操作代碼描述:
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;
文件流是流(stream classes)的子類,所以使用他的一個優點就是能自動繼承其父類的屬性他能很容易的和其他的流類互操作,比如你如果想把一塊動態內存塊寫入磁碟,可以使用一個TFileStream和一個TMemoryStream來完成.