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

From Free Pascal wiki
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.
+
當使用傳統非物件導向的 Pascal 時,你可以使用 TextFile 類型 (type),可以讓你建立檔案並對它寫入字串。
  
 
<Delphi>...
 
<Delphi>...
 
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>
 
...</Delphi>
  
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
+
<Delphi>{$I-} // 關閉檢查。這會使所有錯誤回報轉向存在 IOResult 這個變數裡
{$I+} // Turn it back on</Delphi>
+
{$I+} // 開啟回來</Delphi>
  
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''' - 將變數內容寫入檔案並換行
  
  

Revision as of 10:05, 19 December 2010

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

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

舊方法

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

<Delphi>... type

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

...</Delphi>

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

輸入輸出

IO 是 Pascal 專門用來處理檔案用的。他通常用來對付錯誤訊息。 當用來當編譯器的指令時,你可以這麼用: <Delphi>{$I-} // 關閉檢查。這會使所有錯誤回報轉向存在 IOResult 這個變數裡 {$I+} // 開啟回來</Delphi>

當關閉 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 - 將變數內容寫入檔案並換行


Reference for unit 'System'

Example

A full example of handling a text file of type TextFile:

<Delphi>program FileTest;

{$mode objfpc} // Do not forget this ever

uses

Sysutils;

var

FileVar: TextFile;

begin

 WriteLn('File Test');
 AssignFile(FileVar, 'Test.txt'); // You do not have to put .txt but this is just for now
 {$I-}
 try
   Rewrite(FileVar);  // creating the file
   Writeln(FileVar,'Hello');
 except
   Writeln('ERROR! IORESULT: ' + IntToStr(IOResult));
 end;
 CloseFile(FileVar);
 ReadLn;

end.</Delphi>

Now open the file in any text editor and you will see Hello written to it!

Heres appending to a file(Editing it)

<Delphi>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.</Delphi>

Reading a file:

<Delphi>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); // Reads the whole line from the file
     Writeln(Str); // Writes the line read
   until(EOF(File1)); // EOF(End Of File) The the program will keep reading new lines until there is none.
 except
   Writeln('ERROR IORESULT:', IOResult);
 end;
 {$I+}
 CloseFile(File1);
 Readln;

end.</Delphi>

It is possible to do some file handling using chars instead of strings. This makes it look cool :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.

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.

IO routines

<Delphi>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;</Delphi>


You can load entire file to memory too if it's size is comparatively smaller than available system memory.

<Delphi>begin

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

end;</Delphi>


Text files

In general for text files you can use class TStringList for loading entire file to memory and have simple access their rows.

<Delphi>begin

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

end;</Delphi>