Reputation: 165
I am trying to read from a file. I am using fread(), but I'm unsure whether I'm going about this correctly. I want to create an array of structs and continue "f-reading" from the file into the array like so:
//Get size of file
struct stat st;
stat(document, &st);
int size = st.st_size;
//Create appropriate array size of structs
struct Person person[size];
for(j = 0; j < size; j++) {
fread(person[j].name, 1, 16, fp); //each name is truncated to 15 bytes on the file
fread(person[j].text, 1, 24, fp); //text is truncated to 24 on the file
}
struct Person look like so:
struct Person {
char name[16];
char text[24];
};
Am I using fread() correctly? Thank you.
Upvotes: 1
Views: 145
Reputation: 7610
The code given below is sufficient inside the for loop
fread(person[j], sizeof(struct Person), 1, fp);
Upvotes: 1
Reputation: 182
Increment j by sizeof(struct Person) to avoid fread issue Alternatively you can use feof to check end of file
Upvotes: 0
Reputation: 383
You should check if the fread function call succeeded in reading the expected number of bytes from the data stream:
//Get size of file
struct stat st;
int name_bytes_read, text_bytes_read; // If using C11, use size_t instead
stat(document, &st);
int size = st.st_size;
//Create appropriate array size of structs
struct Person person[size];
for(j = 0; j < size; j++) {
name_bytes_read = fread(person[j].name, 1, 16, fp); //each name is truncated to 15 bytes on the file
if (name_bytes_read != 16) {
fputs ("Error reading name record", stderr);
exit(-1);
}
text_bytes_read = fread(person[j].text, 1, 24, fp); //text is truncated to 24 on the file
if (text_bytes_read != 24) {
fputs ("Error reading text record", stderr);
exit(-1); }
}
Further reading: http://www.thegeekstuff.com/2012/07/c-file-handling
Upvotes: 0