I’m having a bit of trouble getting my program to read in data from a file. The issue is that the file is currently empty. Each time the program is run, a single array of books[] will be populated and written to the file later on in the code. While I’m sure it will work when all 10 structs are in the file, at the moment it’s crashing since the file is empty and it’s trying to read in 10 structs.
Is there a way to read in an unknown number of structs (up to 10) from the file?
struct stock
{
char name[31];
int stock;
};
int main (void)
{
stock books[10];
FILE *fptr;
fptr = fopen("stock.dat", "rb");
fread(books, sizeof(struct stock), 10, fptr);
fclose (fptr);
}
If you know the maximum possible number of structures in the file and can afford to have them all in memory:
otherwise loop and read in chunks: