2014-01-31 103 views
0

所以basicaly我已经二进制文件,这样的结构制成读二进制文件CS

struct data{ 
char name[30]; 
char name2[30]; 
}; 

我想读取数据回从文件结构的数组,但问题是我不知道有多少记录有这文件。有人可以解释我怎么能读整个文件没有给记录里面的记录?

回答

4

您可以打开该文件,检查它的大小:

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 

,记录的数量内将是:

N = sz/sizeof(struct data); 

总之,要小心,如果你只写一个结构数组到一个文件,由于不同的内存对齐,有可能它不会被其他机器读取。您可以使用__attribute__((packed))选项来确保结构相同(但是它是GCC特定的扩展,而不是标准C的一部分)。

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

内存映射您的文件是最好的选择。

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); 

然后智能操作系统会首先从文件中加载数据,并将从内存中逐出最近未被访问的页面。