fseek 函數功能是將文件指針移動到指定的地方,因此可以通過fseek重置文件指針的位置。函數原型:
int fseek(FILE *stream, long offset, int origin);
參數說明:
stream : 待移動的FILE型指針變量
offset:偏移量,每次移動多少個字節
origin: 指針開始的位置
返回值: 如果fseek ()返回值為0,表示執行成功,如果返回值為非0, 則執行失敗。
盡管隨着讀取文件的進行,origin和文件指針的位置都會隨着發生變化,但是在調fseek()函數時,給它傳入的origin參數只能是以下三種之一:
SEEK_CUR : 文件指針目前的位置
SEEK_END : 文件末尾處
SEEK_SET : 文件開始處
當文件以附加文檔形式打開時,當前的文件指針位置是指在上次進行I/O操作之后的文件指針位置上。並不是這次要准備追加文本的目標位置處。如果以附加文檔形式打開一個文件時,這個文件此前沒有進行過I/O操作,那么此時的文件指針指在文件的開始位置處。對於以文本模式打開的流,限制使用fseek函數,因為回車換行符與單行換行符之間的轉換會導致fseek產生意外的結果。fseek只有在下面兩種情況下才能保證當文件以文檔模式打開時能正確使用fseek函數:
1.Seeking with an offset of 0 relative to any of the origin values. (與起始位置相對偏移為0的重置,即沒有改動指針位置)
2.Seeking from the beginning of the file with an offset value returned from a call to ftell.(origin設置為 SEEK_SET ,offset為調用ftell返回的值時進行的指針位置重置情況)
下面透過一個案例來進一步說明fseek的用法:
/* FSEEK.C: This program opens the file FSEEK.OUT and
* moves the pointer to the file's beginning.
*/
#include <stdio.h>
void main( void )
{
FILE *stream;
char line[81];
int result;
stream = fopen( "fseek.out", "w+" );
if( stream == NULL )
printf( "The file fseek.out was not opened\n" );
else
{
fprintf( stream, "The fseek begins here: "
"This is the file 'fseek.out'.\n" );
result = fseek( stream, 23L, SEEK_SET);
if( result )
printf( "Fseek failed" );
else
{
printf( "File pointer is set to middle of first line.\n" );
fgets( line, 80, stream );
printf( "%s", line );
}
fclose( stream );
}
}
剛好"The fseek begins here: " 包括空格在內為23個字符,所以下次輸出從24個字符位置開始:
| Output File pointer is set to middle of first line. This is the file 'fseek.out'.
|
ftell 函數獲取一個文件指針的當前位置,函數原型:
long ftell(FILE *stream);
參數說明:stream : 目標參數的文件指針
ftell 函數目標文件指針的當前位置,如果流是以文本模式打開的, 那么ftell的返回值可能不是文件指針在文件中距離開始文件開始位置的物理字節偏移量,因為文本模式將會有換行符轉換。如果ftell函數執行失敗,則會返回-1L。
案例說明:
/* FTELL.C: This program opens a file named FTELL.C
* for reading and tries to read 100 characters. It
* then uses ftell to determine the position of the
* file pointer and displays this position.
*/
#include <stdio.h>
FILE *stream;
void main( void )
{
long position;
char list[100];
if( (stream = fopen( "ftell.c", "rb" )) != NULL )
{
/* Move the pointer by reading data: */
fread( list, sizeof( char ), 100, stream );
/* Get position after read: */
position = ftell( stream );
printf( "Position after trying to read 100 bytes: %ld\n",
position );
fclose( stream );
}
}
上面的文件首先通過
fread(list,sizeof(char),100,stream) 每次讀取一個char大小的字符,重復讀取100次,因為一個char的大小為1, 所以執行完 fread()這個語句, 此時的stream指針的位置是stream中的位置100處,然后通過ftell(stream)去提取stream流中當前文件指針的位置,那么返回的肯定就是100了,因為它通過fread()函數已經從文件的起始處移動到了100 這個位置了。
| Output Position after trying to read 100 bytes: 100
|
