fsetpos()詳解
函數原型:int fsetpos(FILE *fp, const fpos_t *pos);
頭檔案:#include<stdio.h>
是否是标準函數:是
函數功能:将檔案指針定位在pos指定的位置上。該函數的功能與前面提到的fgetpos相反,是将檔案指針fp按照pos指定的位置在檔案中定位。pos值以内部格式存儲,僅由fgetpos和fsetpos使用。
傳回值:成功傳回0,否則傳回非0。
例程如下 應用fsetpos函數定位檔案指針。
#include <stdio.h>
void main( void )
{
FILE *fp;
fpos_t pos;
char buffer[50];
if( (fp = fopen( "test.txt", "rb" )) == NULL )
printf( "Trouble opening file/n" );
else
{
pos = 10;
if( fsetpos( fp, &pos ) != 0 )
perror( "fsetpos error" );
fread( buffer, sizeof( char ), 16, fp );
printf( "16 bytes at byte %ld: %.16s/n", pos, buffer );
}
fclose( fp );
}
例程說明:
(1)首先,程式以隻讀方式打開名為test.txt的檔案。在這裡,test.txt檔案中已存入字元串This is a test for testing the function of fsetpos.
(2)将pos設定為10。應用fsetpos函數将檔案指針fp按照pos指定的位置在檔案中定位。這樣檔案指針fp指向字元串中test的字母t。
(3)再從新定位的檔案指針開始讀取16個字元到buffer緩沖區,也就是說讀取字元串"test for testing"到緩沖區buffer。
(4)最後顯示結果:16 bytes at byte 10: test for testing 。
fgetpos:取得目前檔案的句柄函數
函數原型:int fgetpos( FILE *stream, fpos_t *pos );
函數功能:取得目前檔案的指針所指的位置,并把該指針所指的位置數存放到pos所指的對象中。pos值以内部格式存儲,僅由fgetpos和fsetpos使用。其中fsetpos的功能與fgetpos相反,為了詳細介紹,将在後節給與說明。
傳回值:成功傳回0,失敗傳回非0,并設定errno。
例程如下:應用fgetpos函數取得目前檔案的指針所指的位置。
#include <string.h>
int main(void)
char string[] = "This is a test";
fp = fopen("test.txt", "w+");
fwrite(string, strlen(string), 1, fp);
fgetpos(fp, &pos);
printf("The file pointer is at byte %ld/n", pos);
fseek(fp,3,0);
fclose(fp);
return 0;
(1)首先,程式以讀寫方式打開一個名為test.txt的檔案,并把字元串"This is a test"寫入檔案。注意:字元串共14個位元組,位址為0~13。用fwrite函數寫入後,檔案指針自動指向檔案最後一個位元組的下一個位置。即這時的fp的值應該是14。