Search code examples
cfilefseek

Use fseek to print any arbitrary record


How do I use fseek to find any arbitrary record and print that record? specifically the third record.
The file format:

first name
last name
gpa

my code (assume the file already exists):

typedef struct
{
    char first [20], last[20];
    double gpa;
} Student;

int main ()
{
    Student student;
    FILE* file = fopen ("gpa.dat", "r+");

    fseek(file, sizeof(Student), SEEK_END);
    fread(&student, sizeof(student), 1, file);

    printf("Name: %s %s\nGPA: %lf\n", student.first, student.last, student.gpa);

    fclose(file);
    return 0;
}

So if the third record is

xxx
yyy
3.56

thats what I want printed


Solution

  • You should use the b modifier in the open mode if you're reading a binary file.

    To get to an arbitrary record, multiply sizeof(Student) by the zero-baed record number. And use SEEK_SET to count from the beginning of the file.

    int main ()
    {
        Student student;
        FILE* file = fopen ("gpa.dat", "rb+");
        int record_num = 3;
    
        fseek(file, record_num * sizeof(Student), SEEK_SET);
        fread(&student, sizeof(student), 1, file);
    
        printf("Name: %s %s\nGPA: %lf\n", student.first, student.last, student.gpa);
    
        fclose(file);
        return 0;
    }