简体   繁体   English

读取二进制文件c

[英]Reading binary files c

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? 有人可以解释一下,如果没有内部记录的记录,我如何读取整个文件?

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). 您可以使用__attribute__((packed))选项来确保结构相同(但这是GCC特定的扩展名,而不是标准C的一部分)。

struct __attribute__((packed)) data {
    char name[30];
    char name2[30];
};

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. 然后,智能操作系统将在首次使用时从文件中加载数据,并从内存中逐出最近未访问过的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM