Difference between revisions of "File Handling In Pascal/zh TW"

From Lazarus wiki
Jump to navigationJump to search
(New page: {FILE HANDLING IN PASCAL} Something most programmers need to know how to do is work with files. Files can be used to save user settings, error logs, and more. Here i am going to teach you ...)
 
m (Fixed syntax highlighting; deleted category included in page template)
 
(7 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{FILE HANDLING IN PASCAL}
+
{{File Handling In Pascal}}
Something most programmers need to know how to do is work with files. Files can be used to save user settings, error logs, and more. Here i am going to teach you how to work with basic text files.
 
  
=Old procedural style=
+
大概所有程式設計師最需要知道的就是如何處理檔案。檔案可以用來儲存使用者的設定,錯誤報告,或更多更多。在這裡我們將教您一些最基本的文字檔案處理。
  
When using files in classic nonobjective pascal, you can use a TextFile type, which allows you to write string into the file or create your own file type.
+
=舊方法=
  
<Delphi>...
+
當使用傳統非物件導向的 Pascal 時,你可以使用 TextFile 類型 (type),可以讓你建立檔案並對它寫入字串。
 +
 
 +
<syntaxhighlight lang=pascal>...
 
type
 
type
  TIntegerFile = file of Integer; // Allows you to write Integers into the file
+
  TIntegerFile = file of Integer; // 可以讓你對檔案寫入整數值
  TPCharFile = file of PChar; // Write PChars into the file :\
+
  TPCharFile = file of PChar; // 將字元 (PChars) 寫入檔案 :\
  TStringFile = file of string; // Write Strings into the file
+
  TStringFile = file of string; // 將字串寫入檔案
...</Delphi>
+
...</syntaxhighlight>
  
If we only did TStringFile = File, then it would be impossible to write anything into it! Also, you cannot write integers directly into TStringFile, because it is a file of strings. Better use the filetype TextFile for writing values of different types.
+
若我們僅用了 TStringFile = File,它將無法寫入任何東西!更無法將整數值寫入 TStringFile,因為它已經是字串型態的檔案。最好是使用 TextFile 的型態,它才能寫入各種不同形態的內容。
  
==IO==
+
==輸入輸出==
  
IO is the file handling thingy for pascal. It is used for getting errors.
+
IO 是 Pascal 專門用來處理檔案用的。他通常用來對付錯誤訊息。
Since it is a compiler directive, you have to do this:
+
當用來當編譯器的指令時,你可以這麼用:
<Delphi>{$I-} // Turn off checking. This way all errors go into the IOResult variable
+
<syntaxhighlight lang=pascal>{$I-} // 關閉檢查。這會使所有錯誤回報轉向存在 IOResult 這個變數裡
{$I+} // Turn it back on</Delphi>
+
{$I+} // 開啟回來</syntaxhighlight>
  
By disabling (Turning off) IO it all goes into the IOResult variable. This is an cardinal type(Numbers). So, if you want to write it, you have to use the IntToStr function. Different numbers mean different errors. So you may want to check here for the different errors: [http://www.efg2.com/Lab/Library/Delphi/IO/IOResult.htm]
+
當關閉 IO 時他所有的輸出都會轉到 IOResult 變數裡。他是主要數字型態的變數 (cardinal type; Numbers)。所以如果你想要對它做寫入,你得使用 IntToStr 函式。不同的數字代表不同的錯誤。你可以參看這裡來了解每個不同的錯誤:[http://www.efg2.com/Lab/Library/Delphi/IO/IOResult.htm]
  
==File procedures==
+
==處理檔案的程序==
  
These file handling procedures and functions are located in unit system.
+
以下列出所有系統裡用來做檔案處理時會用的程序和函式。
  
* '''Assign''' - Assign a name to a file
+
* '''Assign''' - 指派名稱給檔案
* '''Append''' - Opens an existing file for appending data to end of file and editing it
+
* '''Append''' - 開啟已經存在的檔案,在檔案的末端接續額外內容並編輯它
* '''BlockRead''' -  Read data from an untyped file into memory
+
* '''BlockRead''' -  對未定型態的檔案將其內容讀入到記憶體
* '''BlockWrite''' - Write data from memory to an untyped file
+
* '''BlockWrite''' - 將記憶體中的內容寫入未定型態的檔案
* '''Close''' - Close opened file
+
* '''Close''' - 關閉開啟中的檔案
* '''EOF''' - Check for end of file
+
* '''EOF''' - 檢查是否為檔案末端
* '''Erase''' - Erase file from disk
+
* '''Erase''' - 將檔案從磁碟上刪除
* '''FilePos''' - Get position in file
+
* '''FilePos''' - 取得檔案定位
* '''FileSize''' - Get size of file
+
* '''FileSize''' - 取得檔案大小
* '''Flush''' - Write file buffers to disk
+
* '''Flush''' - 將檔案暫存寫入磁碟
* '''IOResult''' - Return result of last file IO operation
+
* '''IOResult''' - 回傳最後一個檔案 IO 操作的結果
* '''Read''' - Read from a text file into variable
+
* '''Read''' - 將文字檔寫入變數
* '''ReadLn''' - Read from a text file into variable and goto next line
+
* '''ReadLn''' - 將文字檔寫入變數並換行
* '''Reset''' - Opens a file for reading
+
* '''Reset''' - 開啟一個檔案準備讀取
* '''Rewrite''' - Open file for writing
+
* '''Rewrite''' - 開啟一個檔案準備寫入
* '''Seek''' - Change position in file
+
* '''Seek''' - 變更檔案中的定位
* '''SeekEOF''' - Set file position to end of file
+
* '''SeekEOF''' - 將檔案定位指到其結尾處
* '''SeekEOLn''' - Set file position to end of line
+
* '''SeekEOLn''' - 將檔案定位指到該行結尾處
* '''Truncate''' - Truncate the file at position
+
* '''Truncate''' - 於檔案定位處將內容清空
* '''Write''' - Write variable to a text file
+
* '''Write''' - 將變數內容寫入檔案
* '''WriteLn''' - Write variable to a text file and append newline
+
* '''WriteLn''' - 將變數內容寫入檔案並換行
  
  
[http://www.freepascal.org/docs-html/rtl/system/index-5.html Reference for unit 'System']
+
[http://www.freepascal.org/docs-html/rtl/system/index-5.html 參考單元 'System']
  
==Example==
+
==範例==
  
A full example of handling a text file of type TextFile:
+
以下為處理一型態是 TextFile 的文字檔的完整範例:
  
<Delphi>program FileTest;
+
<syntaxhighlight lang=pascal>program FileTest;
  
{$mode objfpc} // Do not forget this ever
+
{$mode objfpc} // 永遠都不要放記這個
  
 
uses
 
uses
Line 69: Line 70:
 
begin
 
begin
 
   WriteLn('File Test');
 
   WriteLn('File Test');
   AssignFile(FileVar, 'Test.txt'); // You do not have to put .txt but this is just for now
+
   AssignFile(FileVar, 'Test.txt'); // 你不一定需要 .txt,在這裡我們這麼做
 
   {$I-}
 
   {$I-}
 
   try
 
   try
     Rewrite(FileVar);  // creating the file
+
     Rewrite(FileVar);  // 建立檔案
 
     Writeln(FileVar,'Hello');
 
     Writeln(FileVar,'Hello');
 
   except
 
   except
Line 79: Line 80:
 
   CloseFile(FileVar);
 
   CloseFile(FileVar);
 
   ReadLn;
 
   ReadLn;
end.</Delphi>
+
end.</syntaxhighlight>
  
Now open the file in any text editor and you will see Hello written to it!
+
現在你再用任何的文字編輯器來開啟這支文字檔,你會看到一個 Hello 寫在裡面!
  
Heres appending to a file(Editing it)
+
在來我們接著加入內容 (編輯它)
  
<Delphi>program EditFile;
+
<syntaxhighlight lang=pascal>program EditFile;
  
  
Line 108: Line 109:
 
   CloseFile(File1);
 
   CloseFile(File1);
 
   Readln;
 
   Readln;
end.</Delphi>
+
end.</syntaxhighlight>
  
Reading a file:
+
讀取檔案:
  
<Delphi>program ReadFile;
+
<syntaxhighlight lang=pascal>program ReadFile;
  
  
Line 131: Line 132:
 
     Reset(File1);
 
     Reset(File1);
 
     repeat
 
     repeat
       Readln(File1, Str); // Reads the whole line from the file
+
       Readln(File1, Str); // 對檔案讀取整行
       Writeln(Str); // Writes the line read
+
       Writeln(Str); // 將讀到的一整行寫入
     until(EOF(File1)); // EOF(End Of File) The the program will keep reading new lines until there is none.
+
     until(EOF(File1)); // EOF (檔案結尾) 迴圈會一直進行讀取直到讀不到內容為止。
 
   except
 
   except
 
     Writeln('ERROR IORESULT:', IOResult);
 
     Writeln('ERROR IORESULT:', IOResult);
Line 140: Line 141:
 
   CloseFile(File1);
 
   CloseFile(File1);
 
   Readln;
 
   Readln;
end.</Delphi>
+
end.</syntaxhighlight>
  
It is possible to do some file handling using chars instead of strings. This makes it look cool :D.
+
在這裡的處理你也可以改用字元替代字串。這會讓它看起來很酷 :D。
  
=Object style=
+
=物件導向做法=
  
Most of string handling classes have ability to load and save content from/to file. These methods are usually named SaveToFile and LoadFromFile.
+
大部份的檔案處理類別都可以直接著檔案進行讀取/存入。這些方法一般會取名為 SaveToFile 和 LoadFromFile。
  
==Binary files==
+
==二進位==
  
For opening files for direct access TFileStream should be used. This class is encapsulation for system procedures FileOpen, FileCreate, FileRead, FileWrite, FileSeek and FileClose which resides in unit FileUtil. This class is basically platform independent as these procedures have specific implementation for each platform.
+
若要進行直接存取可以使用 TFileStream 。這個類別將系統程序 FileOpen,FileCreate,FileRead,FileWrite,FileSeek 與 FileClose 全都包裝好放置於一起,歸屬於 FileUtil 單元。這個類型基本上算跨平台的,不過不同平台會有一些不同的實作方式。
  
[http://www.freepascal.org/docs-html/rtl/sysutils/ioroutines.html IO routines]
+
[http://www.freepascal.org/docs-html/rtl/sysutils/ioroutines.html IO 例行程序]
  
<Delphi>var
+
<syntaxhighlight lang=pascal>var
 
   Buffer: array[0..10000] of Byte;
 
   Buffer: array[0..10000] of Byte;
 
begin
 
begin
Line 164: Line 165:
 
     Free;
 
     Free;
 
   end;
 
   end;
end;</Delphi>
+
end;</syntaxhighlight>
  
  
You can load entire file to memory too if it's size is comparatively smaller than available system memory.
+
如果檔案比起你的系統記憶體比起來小的多,你也可以將整個檔案載入到記憶體內。
  
<Delphi>begin
+
<syntaxhighlight lang=pascal>begin
 
   with TMemoryStream.Create do  
 
   with TMemoryStream.Create do  
 
   try
 
   try
Line 179: Line 180:
 
     Free;
 
     Free;
 
   end;
 
   end;
end;</Delphi>
+
end;</syntaxhighlight>
  
  
==Text files==
+
==文字檔案==
  
In general for text files you can use class TStringList for loading entire file to memory and have simple access their rows.
+
一般針對文字檔你可以使用 TStringList 類別來載入整支檔案到記憶體中,然後一行行來存取。
  
<Delphi>begin
+
<syntaxhighlight lang=pascal>begin
 
   with TStringList.Create do  
 
   with TStringList.Create do  
 
   try
 
   try
Line 194: Line 195:
 
     Free;
 
     Free;
 
   end;
 
   end;
end;</Delphi>
+
end;</syntaxhighlight>
 
 
 
 
[[Category:Tutorials]]
 

Latest revision as of 00:39, 15 February 2020

العربية (ar) English (en) español (es) suomi (fi) français (fr) 日本語 (ja) русский (ru) 中文(中国大陆)‎ (zh_CN) 中文(台灣)‎ (zh_TW)

大概所有程式設計師最需要知道的就是如何處理檔案。檔案可以用來儲存使用者的設定,錯誤報告,或更多更多。在這裡我們將教您一些最基本的文字檔案處理。

舊方法

當使用傳統非物件導向的 Pascal 時,你可以使用 TextFile 類型 (type),可以讓你建立檔案並對它寫入字串。

...
type
 TIntegerFile = file of Integer; // 可以讓你對檔案寫入整數值
 TPCharFile = file of PChar; // 將字元 (PChars) 寫入檔案 :\
 TStringFile = file of string; // 將字串寫入檔案
...

若我們僅用了 TStringFile = File,它將無法寫入任何東西!更無法將整數值寫入 TStringFile,因為它已經是字串型態的檔案。最好是使用 TextFile 的型態,它才能寫入各種不同形態的內容。

輸入輸出

IO 是 Pascal 專門用來處理檔案用的。他通常用來對付錯誤訊息。 當用來當編譯器的指令時,你可以這麼用:

{$I-} // 關閉檢查。這會使所有錯誤回報轉向存在 IOResult 這個變數裡
{$I+} // 開啟回來

當關閉 IO 時他所有的輸出都會轉到 IOResult 變數裡。他是主要數字型態的變數 (cardinal type; Numbers)。所以如果你想要對它做寫入,你得使用 IntToStr 函式。不同的數字代表不同的錯誤。你可以參看這裡來了解每個不同的錯誤:[1]

處理檔案的程序

以下列出所有系統裡用來做檔案處理時會用的程序和函式。

  • Assign - 指派名稱給檔案
  • Append - 開啟已經存在的檔案,在檔案的末端接續額外內容並編輯它
  • BlockRead - 對未定型態的檔案將其內容讀入到記憶體
  • BlockWrite - 將記憶體中的內容寫入未定型態的檔案
  • Close - 關閉開啟中的檔案
  • EOF - 檢查是否為檔案末端
  • Erase - 將檔案從磁碟上刪除
  • FilePos - 取得檔案定位
  • FileSize - 取得檔案大小
  • Flush - 將檔案暫存寫入磁碟
  • IOResult - 回傳最後一個檔案 IO 操作的結果
  • Read - 將文字檔寫入變數
  • ReadLn - 將文字檔寫入變數並換行
  • Reset - 開啟一個檔案準備讀取
  • Rewrite - 開啟一個檔案準備寫入
  • Seek - 變更檔案中的定位
  • SeekEOF - 將檔案定位指到其結尾處
  • SeekEOLn - 將檔案定位指到該行結尾處
  • Truncate - 於檔案定位處將內容清空
  • Write - 將變數內容寫入檔案
  • WriteLn - 將變數內容寫入檔案並換行


參考單元 'System'

範例

以下為處理一型態是 TextFile 的文字檔的完整範例:

program FileTest;

{$mode objfpc} // 永遠都不要放記這個

uses
 Sysutils;

var
 FileVar: TextFile;

begin
  WriteLn('File Test');
  AssignFile(FileVar, 'Test.txt'); // 你不一定需要 .txt,在這裡我們這麼做
  {$I-}
  try
    Rewrite(FileVar);  // 建立檔案
    Writeln(FileVar,'Hello');
  except
    Writeln('ERROR! IORESULT: ' + IntToStr(IOResult));
  end;
  CloseFile(FileVar);
  ReadLn;
end.

現在你再用任何的文字編輯器來開啟這支文字檔,你會看到一個 Hello 寫在裡面!

在來我們接著加入內容 (編輯它)

program EditFile;


{$mode objfpc}

uses
 Sysutils;

var
 File1: TextFile;
 
begin
  WriteLn('Append file');
  AssignFile(File1, 'File.txt');
  {$I-}
  try
    Append(File1, 'Some Text');
  except
    Writeln('ERROR IORESULT:' + IntToStr(IOResult));
  end;
  {$I+}
  CloseFile(File1);
  Readln;
end.

讀取檔案:

program ReadFile;


{$mode objfpc}

uses
 Sysutils;

var
 File1: TextFile;
 Str: String;
 
begin
  Writeln('File Reading:');
  AssignFile(File1, 'File,txt');
  {$I-}
  try
    Reset(File1);
    repeat
      Readln(File1, Str); // 對檔案讀取整行
      Writeln(Str); // 將讀到的一整行寫入
    until(EOF(File1)); // EOF (檔案結尾) 迴圈會一直進行讀取直到讀不到內容為止。
  except
    Writeln('ERROR IORESULT:', IOResult);
  end;
  {$I+}
  CloseFile(File1);
  Readln;
end.

在這裡的處理你也可以改用字元替代字串。這會讓它看起來很酷 :D。

物件導向做法

大部份的檔案處理類別都可以直接著檔案進行讀取/存入。這些方法一般會取名為 SaveToFile 和 LoadFromFile。

二進位

若要進行直接存取可以使用 TFileStream 。這個類別將系統程序 FileOpen,FileCreate,FileRead,FileWrite,FileSeek 與 FileClose 全都包裝好放置於一起,歸屬於 FileUtil 單元。這個類型基本上算跨平台的,不過不同平台會有一些不同的實作方式。

IO 例行程序

var
  Buffer: array[0..10000] of Byte;
begin
  with TFileStream.Create('SomeFile.bin', fmCreate) do 
  try
    Seek('Hello');
    Write(Buffer, SizeOf(Buffer));
  finally
    Free;
  end;
end;


如果檔案比起你的系統記憶體比起來小的多,你也可以將整個檔案載入到記憶體內。

begin
  with TMemoryStream.Create do 
  try
    LoadFromFile('SomeFile.bin');
    Seek(0, soEnd);
    Write(Ord('A'), 1);
    SaveToFile('SomeFile.bin');
  finally
    Free;
  end;
end;


文字檔案

一般針對文字檔你可以使用 TStringList 類別來載入整支檔案到記憶體中,然後一行行來存取。

begin
  with TStringList.Create do 
  try
    Add('Hello');
    SaveToFile('SomeFile.txt');
  finally
    Free;
  end;
end;