apaul30
apaul30

Reputation: 3

Improper Binary File Read

I am new to C and am trying to read and write structures to a .dat file. When I add the data, I see the characters in the .dat file. However, I am unable to read the data and my code outputs nothing when it should output "val" for every occurrence of a structure.

I have looked at numerous sources but I cannot find how my code differs to those.

https://www.geeksforgeeks.org/readwrite-structure-file-c/ This website was used to initially understand how to do this.

Read/Write to binary files in C I used this to see how my code could be fixed but the solution did not help.

I tried changing the statement in the while loop.

struct person
{
    int id;
    char lastName[15];
    char firstName[15];
    char age[4];
};


int main(void) {
  //create new file
  FILE *fp = fopen("file.dat", "wb+");

  struct person a = {10, "Smith", "John", 25};
  fwrite(&a, sizeof(a), 1, fp);

  struct person b = {2, "Ali", "Jon", 12};
  fwrite(&b, sizeof(b), 1, fp);

 struct person c = {19, "Walter", "Martha", 82};
  fwrite(&c, sizeof(c), 1, fp);

  struct person p; 
  while(fread(&p, sizeof(p), 1, fp))
  printf("val");
}

Currently, it should print 3 "Vals" as there are three persons being added to the dat file. However, nothing is being printed out.

I appreciate the help.

Upvotes: 0

Views: 99

Answers (2)

Nitin Jadhav
Nitin Jadhav

Reputation: 527

If you want to read back and print then try to capture the start position of the file before writing the file with fpos_t and fgetpos() . Later after writing to file set back the initial position using fsetpos() and use fget() to read the content and print them. Check the modified code as below-

#include<stdio.h>
#include<stdlib.h>

struct person
{
    int id;
    char lastName[15];
    char firstName[15];
    char age[4];
};


int main(void) {
  //create new file
  FILE *fp = fopen("file.dat", "wb+");
  fpos_t position;


  struct person a = {10, "Smith", "John", "25"};
  fwrite(&a, sizeof(a), 1, fp);

  struct person b = {2, "Ali", "Jon", "12"};
  fwrite(&b, sizeof(b), 1, fp);

  struct person c = {19, "Walter", "Martha", "82"};
  fwrite(&c, sizeof(c), 1, fp);

  fseek(fp, 0, SEEK_SET);

  struct person p; 
  while(fread((void *)&p, sizeof(p),1,fp)==1)
  {
    printf("%d\n",p.id);
    printf("%s\n",p.lastName);
    printf("%s\n",p.firstName);
    printf("%s\n",p.age);    
    printf("\n");
  }
}

Upvotes: 0

Swordfish
Swordfish

Reputation: 13134

When you are done writing the records, the file pointer (the "cursor", the position you are reading/writing) is at the end of the file. You have to set that position back to the begin of the file by using rewind(), fseek() or fsetpos() before trying to read from the file.

Upvotes: 2

Related Questions