Reputation: 75
So basicaly I have binary file made with such structure
struct data{
char name[30];
char name2[30];
};
I want to read data back into array of structs from file but the problem is I dont know how many records there are in this file. Could somebody explain how could I read whole file not given ammout of records inside?
Upvotes: 0
Views: 171
Reputation: 3098
You can open the file, check it's size:
fseek(fp, 0L, SEEK_END); // Go at the end
sz = ftell(fp); // Tell me the current position
fseek(fp, 0L, SEEK_SET); // Go back at the beginning
And the number of records inside will be:
N = sz/sizeof(struct data);
Anyway, be careful that if you just write an array of structures to a file, it's possible that it will not be readable others machines, due to different memory alignment. You can use the __attribute__((packed))
option to be sure that the structure will be the same (but it's a GCC specific extension, not part of standard C).
struct __attribute__((packed)) data {
char name[30];
char name2[30];
};
Upvotes: 4
Reputation: 22552
Memory mapping your file is your best bet.
int fd = open(filename, O_RDONLY);
struct stat fdstat;
fstat(fd, &fdstat);
struct data * file_contents = mmap(NULL, fdstat.st_size
, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
// assuming the file contains only those structs
size_t num_records = fdstat.st_size / sizeof(*file_contents);
An intelligent OS will then load the data from the file on a first-use basis and will evict pages from memory that have not been accessed recently.
Upvotes: 0