48 การใช้ไฟล์ random access


  • fseek syntax

    int fseek (FILE *p , long offset ,int origin );

    p คือไฟล์พอร์ยเตอร์

    offset คือจำนวนไบต์ที่ต้องการไป. ถ้าเป็นบวก จะก้าวไปข้างหน้า ถ้าเป็นลบ จะถอยไปข้างหลัง

    origin คือ ค่าคงที่ระหว่าง 0 1 และ 2

    ค่าคงที่ค่าตัวเลขความสัมพันธ์กับพอร์ยเตอร์
    SEEK_SET0จุดเริ่มต้น
    SEEK_CUR1xจุดปัจจุบันที่พอร์ยเตอร์กำลังชี้อยู่xx
    SEEK_END2จุดสุดท้ายของไฟล์ EOF

#include <stdio.h>
#include <string.h>
typedef struct person
{
int age;
char country[5];
}Person;
int main(void)
{
char *fileName = "person.txt";
FILE *fout = fopen(fileName,"wb");
if(fout==NULL) exit(-1);
Person emily = {19} , joseph = {20} , tom = {21},
david={23},jack={24};
strcpy(emily.country ,"1AUS");
strcpy(joseph.country ,"2TH");
strcpy(tom.country ,"3HK");
strcpy(david.country ,"4IND");
strcpy(jack.country ,"5USA");
fwrite(&emily,sizeof(Person),1,fout);
fwrite(&joseph,sizeof(Person),1,fout);
fwrite(&tom,sizeof(Person),1,fout);
fwrite(&david,sizeof(Person),1,fout);
fwrite(&jack,sizeof(Person),1,fout);
fclose(fout);
FILE *fin = fopen(fileName,"rb");
if(fin==NULL) exit(-1);
Person x;
fread(&x,sizeof(Person),1,fin);
printf("Age : %d , Country %s \n",x.age,x.country);
fread(&x, sizeof(Person), 1, fin);
printf("Age : %d , Country %s \n", x.age, x.country);
fread(&x, sizeof(Person), 1, fin);
printf("Age : %d , Country %s \n", x.age, x.country);
fseek(fin, -4 * sizeof(Person) , 2);
fread(&x, sizeof(Person), 1, fin);
printf("Age : %d , Country %s \n", x.age, x.country);
//
// fread(&x, sizeof(Person), 1, fin);
// printf("Age : %d , Country %s \n", x.age, x.country);
fclose(fin);
return 0;
}