首先定義結構體
将結構體寫入
讀取檔案
可以用下面的測試代碼
其中用到的是c語言操作檔案的幾個方法,特别要提一下的是fseek這個方法
功 能 重定位流(資料流/檔案)上的檔案内部位置指針
注意:不是定位檔案指針,檔案指針指向檔案/流。位置指針指向檔案内部的位元組位置,随着檔案的讀取會移動,檔案指針如果不重新指派将不會改變指向别的檔案。
用 法 int fseek(file *stream, long offset, int fromwhere);
描 述 函數設定檔案指針stream的位置。如果執行成功,stream将指向以fromwhere(偏移起始位置:檔案頭0,目前位置1,檔案尾2)為基準,偏移offset(指針偏移量)個位元組的位置。如果執行失敗(比如offset超過檔案自身大小),則不改變stream指向的位置。
傳回值 成功,傳回0,否則傳回其他值。
fseek position the file(檔案) position(位置) pointer(指針) for the file referenced by stream to the byte location calculated by offset.
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>
#define n 5
typedef struct student {
long sno;
char name[10];
float score[3];
} stu;
void fun(char *filename, stu n)
file *fp;
fp = fopen(filename, "rb+");
fseek(fp, -1l*sizeof(stu),seek_end);
fwrite(&n, sizeof(stu), 1, fp);
fclose(fp);
void main()/*修改覆寫最後一個學生資料*/
stu t[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}};
stu n={10006,"zhaosi", 55, 70, 68}, ss[n];
int i,j; file *fp;
fp = fopen("student.dat", "wb");
fwrite(t, sizeof(stu), n, fp);
fp = fopen("student.dat", "rb");
fread(ss, sizeof(stu), n, fp);
printf("\nthe original data :\n\n");
for (j=0; j<n; j++)
printf("\nno: %ld name: %-8s scores: ",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("\nthe data after modifing :\n\n");
注意事項 fseek函數的檔案指針,應該為已經打開的檔案。如果沒有打開的檔案,那麼将會出現錯誤。 fseek函數也可以這樣了解,相當于在檔案當中定位。這樣在讀取規律性存儲才檔案時可以利用其offset偏移量讀取檔案上任意的内容。