C語言 fseek(f,0,SEEK_SET)函數案例詳解
fseek(f,0,SEEK_SET);
意思是把文件指針指向文件的開頭
fseek
函數名: fseek
功 能: 重定位流上的文件指針
用 法: int fseek(FILE *stream, long offset, int fromwhere);
描 述: 函數設置文件指針stream的位置。如果執行成功,stream將指向以fromwhere為基準,偏移offset個字節的位置。如果執行失敗(比如offset超過文件自身大小),則不改變stream指向的位置。
返回值: 成功,返回0,否則返回其他值。
fseek position the file position pointer for the file referenced by stream to the byte location calculated by offset.
程序例:
#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_SET: 文件開頭
SEEK_CUR: 當前位置
SEEK_END: 文件結尾
其中SEEK_SET,SEEK_CUR和SEEK_END和依次為0,1和2.
簡言之:
fseek(fp,100L,0);把fp指針移動到離文件開頭100字節處;
fseek(fp,100L,1);把fp指針移動到離文件當前位置100字節處;
fseek(fp,100L,2);把fp指針退回到離文件結尾100字節處。
使用實例:
#include<stdio.h> #defineN5 typedefstructstudent{ longsno; charname[10]; floatscore[3]; }STU; voidfun(char*filename,STUn) { FILE*fp; fp=fopen(filename,"rb+"); fseek(fp,-1L*sizeof(STU),SEEK_END); fwrite(&n,sizeof(STU),1,fp); fclose(fp); } voidmain()/*修改覆蓋最後一個學生數據*/ { STUt[N]={{10001,"MaChao",91,92,77},{10002,"CaoKai",75,60,88}, {10003,"LiSi",85,70,78},{10004,"FangFang",90,82,87}, {10005,"ZhangSan",95,80,88}}; STUn={10006,"ZhaoSi",55,70,68},ss[N]; inti,j;FILE*fp; fp=fopen("student.dat","wb"); fwrite(t,sizeof(STU),N,fp); fclose(fp); fp=fopen("student.dat","rb"); fread(ss,sizeof(STU),N,fp); fclose(fp); printf("\nTheoriginaldata:\n\n"); for(j=0;j<N;j++) { printf("\nNo:%ldName:%-8sScores:",ss[j].sno,ss[j].name); for(i=0;i<3;i++)printf("%6.2f",ss[j].score[i]); printf("\n"); } fun("student.dat",n); printf("\nThedataaftermodifing:\n\n"); fp=fopen("student.dat","rb"); fread(ss,sizeof(STU),N,fp); fclose(fp); for(j=0;j<N;j++) { printf("\nNo:%ldName:%-8sScores:",ss[j].sno,ss[j].name); for(i=0;i<3;i++)printf("%6.2f",ss[j].score[i]); printf("\n"); } }
到此這篇關於C語言 fseek(f,0,SEEK_SET)函數案例詳解的文章就介紹到這瞭,更多相關C語言 fseek(f,0,SEEK_SET)函數內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!