How to use fpos_t, fgetpos and fsetpos in C

1 Answer

0 votes
#include <stdio.h>
#include <assert.h>

#define SIZE 5

int main(void)
{
    FILE* fp = fopen("data.bin", "wb");

    assert(fp);
    size_t rv = fwrite((double[SIZE]) { 3.14, 1.24, 4.38, 5.63, 7.89 }, sizeof(double), SIZE, fp);
    assert(rv == SIZE);
    fclose(fp);

    fp = fopen("data.bin", "rb");
    fpos_t pos;
    fgetpos(fp, &pos); // store start of file in pos
    
    double d;
    rv = fread(&d, sizeof d, 1, fp); // read the first double value from file
    assert(rv == 1);
    printf("First value in the file: %.2f\n", d);

    fsetpos(fp, &pos); // move file position back to the start of the file
    rv = fread(&d, sizeof d, 1, fp); // read the first double from file 
    assert(rv == 1);
    printf("First value in the file: %.2f\n", d);
    fclose(fp);
}


/*

First value in the file: 3.14
First value in the file: 3.14

*/

 



answered Sep 29, 2024 by avibootz

Related questions

1 answer 203 views
1 answer 134 views
134 views asked Feb 3, 2023 by avibootz
1 answer 978 views
...