Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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 189 views
1 answer 116 views
116 views asked Feb 3, 2023 by avibootz
1 answer 950 views
...