fseek
函數名: fseek
功 能: 重定位流上的文件指針
用 法: int fseek(FILE *stream, long offset, int fromwhere);
描 述: 函數設置文件指針stream的位置。如果執行成功,stream將指向以fromwhere為基準,偏移offset個字節的位置。如果執行失敗(比如offset超過文件自身大小),則不改變stream指向的位置。
返回值: 成功,返回0,否則返回其他值。
程序例:
#include <stdio.h>
long filesize(FILE *stream);
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test");
printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));
fclose(stream);
return 0;
}
long filesize(FILE *stream)
{
long curpos, length;
curpos = ftell(stream);
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
fseek(stream, curpos, SEEK_SET);
return length;
}
int fseek( FILE *stream, long offset, int origin );
第一個參數stream為文件指針
第二個參數offset為偏移量,整數表示正向偏移,負數表示負向偏移
第三個參數origin設定從文件的哪里開始偏移,可能取值為:SEEK_CUR、 SEEK_END 或 SEEK_SET
SEEK_CUR: 當前位置
SEEK_END: 文件結尾
SEEK_SET: 文件開頭
其中SEEK_CUR,SEEK_END和SEEK_SET依次為1,2和0。
fread
C語言庫函數名: fread
功 能: 從一個流中讀數據
函數原型: int fread(void *ptr, int size, int nitems, FILE *stream);
參 數:用于接收數據的地址(字符型指針)(ptr)
單個元素的大小(size)
元素個數(nitems)
提供數據的文件指針(stream)
返回值:成功讀取的元素個數
程序例:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char msg[] = "this is a test";
char buf[20];
if ((stream = fopen("DUMMY.FIL", "w+"))
== NULL)
{
fprintf(stderr,
"Cannot open output file.\n");
return 1;
}
/* write some data to the file */
fwrite(msg, strlen(msg)+1, 1, stream);
/* seek to the beginning of the file */
fseek(stream, 0, SEEK_SET);
/* read the data and display it */
fread(buf, strlen(msg)+1, 1,stream);
printf("%s\n", buf);
fclose(stream);
return 0;
}