Share via


Seek 函式

更新:2007 年 11 月

傳回指定使用 FileOpen 函式開啟的檔案中目前讀取/寫入位置的 Long,或設定使用 FileOpen 函式開啟的檔案中下一個讀取/寫入作業的位置。

My 功能提供比 Seek 更強的檔案 I/O 作業產能和效能。如需詳細資訊,請參閱 My.Computer.FileSystem 物件

Public Overloads Function Seek( _
   ByVal FileNumber As Integer _
) As Long
' -or-
Public Overloads Sub Seek( _
   ByVal FileNumber As Integer, _
   ByVal Position As Long _
)

參數

  • FileNumber
    必要項,包含有效檔案數目的 Integer。

  • Position
    必要項,介於範圍 1 -2,147,483,647 之間 (含) 的數字,表示下一個讀取/寫入作業應發生的位置。

例外狀況

例外狀況類型

錯誤代碼

條件

IOException

52

FileNumber 不存在。

IOException

54

檔案模式無效。

如果將使用非結構化錯誤處理的 Visual Basic 6.0 應用程式升級,請參閱「錯誤代碼」資料行 (您可以將錯誤代碼與 Number 屬性 (Err 物件) 比對)。但是,請盡可能考慮以 Visual Basic 的結構化例外處理概觀 取代這類錯誤控制項。

備註

Seek 會傳回介於 1 和 2,147,483,647 (等於 2^31 – 1) 之間 (含) 的值。

以下說明每個檔案存取模式的傳回值:

模式

傳回值

Random

下一筆讀取或寫入的資料錄號碼

Binary, Input, Output, Append

下一個作業發生的位元組位置。檔案中的第一個位元組位於位置 1,第二個位元組位於位置 2,依此類推。

範例

這個範例使用 Seek 函式傳回目前的檔案位置。這個範例假設 TestFile 是包含 Record 結構資料錄的檔案。

Structure Record   ' Define user-defined type.
   Dim ID As Integer
   Dim Name As String
End Structure

對於在 Random 模式下開啟的檔案而言,Seek 會傳回下一筆資料錄的編號。

FileOpen(1, "TESTFILE", OpenMode.Random)
Do While Not EOF(1)   
   WriteLine(1,Seek(1))   ' Write record number.
   FileGet(1, MyRecord, -1)   ' Read next record.
Loop
FileClose(1)

對於不是在 Random 模式下開啟的檔案而言,Seek 會傳回下一個作業發生的位元組位置。假設 TestFile 是個內含幾行文字的檔案。

' Report character position at beginning of each line.
Dim TextLine As String
FileOpen(1, "TESTFILE", OpenMode.Input)   ' Open file for reading.
While Not EOF(1)   
' Read next line.
   TextLine = LineInput(1)
   ' Position of next line.
   MsgBox(Seek(1))
End While
FileClose(1)

這個範例使用 Seek 函式設定檔案中下一個讀取或寫入的位置。這個範例假設 People.txt 是包含 Record 結構資料錄的檔案。

Structure TestRecord
   Dim Name As String
   Dim ID As Integer
End Structure

對於不是在 Random 模式下開啟的檔案而言,Seek 會設定下一個作業發生的位元組位置。假設 TestFile 是個內含幾行文字的檔案。

Dim someText As String = "This is a test string."
' Open file for output.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Move to the third character.
Seek(1, 3)
Input(1, someText)
Console.WriteLine(someText)
FileClose(1)

智慧型裝置開發人員注意事項

不支援這個函式。

需求

命名空間 (Namespace)︰Microsoft.VisualBasic

**模組︰**FileSystem

組件:Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

FileGet 函式

Loc 函式

FileOpen 函式

FilePut 函式

IOException

其他資源

在 Visual Basic 中讀取檔案

在 Visual Basic 中寫入檔案