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.