C 程式設計/stdio.h/fseek
外觀
fseek 是 C 語言標準庫中的一個函式,包含在 stdio.h 檔案中。它的作用是改變指定流的檔案位置指示器。由於 fseek 在許多平臺上使用 32 位值,因此它最多隻能進行 2 千兆位元組的定址。對於更大的偏移量,可以使用 fseeko64。
int fseek(FILE *stream_pointer, long offset, int origin);
fseek 函式將與流關聯的檔案指標移動到一個新的位置,該位置距離 origin 偏移位元組數。
引數含義
- stream_pointer 是指向流 FILE 結構的指標,該結構的檔案位置指示器應該被改變;
- offset 是一個 long 整數,它指定檔案位置指示器應該放置在距離 origin 多少位元組的地方;
- origin 是一個整數,它指定原點位置。它可以是
- SEEK_SET: 原點是流的開頭
- SEEK_CUR: 原點是當前位置
- SEEK_END: 原點是流的末尾
返回值是一個 integer,表示
- 0 (零) : 函式在流中成功執行
- 非零 : 發生錯誤
- 在無法進行定址的裝置上,返回值是未定義的。
請注意,每個錯誤號都有不同的含義。可以透過檢查 errno.h 來了解含義。
#include <stdio.h>
int main(int argc, char **argv) {
FILE *file_handle;
long int file_length;
file_handle = fopen("file.bin","rb");
if(fseek(file_handle, 0, SEEK_END)) {
puts("Error while seeking to end of file");
return 1;
}
file_length = ftell(file_handle);
if (file_length < 0) {
puts("Error while reading file position");
return 2;
}
printf("File length: %d bytes\n", file_length);
fclose(file_handle);
return 0;
}
這段程式程式碼以只讀模式開啟名為 file.bin 的檔案。檔案的長度是透過定址到檔案末尾,然後讀取檔案指標的位置來確定的。