从文件读取未知数量的结构-C [英] Reading unknown number of structs from file - C

查看:100
本文介绍了从文件读取未知数量的结构-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我的程序从文件中读取数据时遇到麻烦.问题是该文件当前为空.每次运行该程序时,将填充单个book []数组,并稍后在代码中将其写入文件.虽然我确定所有10个结构都在文件中时它会起作用,但由于文件为空并且正在尝试读取10个结构,此刻它崩溃了.

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.

是否可以从文件中读取未知数量的结构(最多10个)?

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:

int main (void)
{
    #define MAX_BOOKS 10
    stock books[MAX_BOOKS];
    size_t cnt_books = 0;
    FILE *fptr;
    fptr = fopen("stock.dat", "rb");
    cnt_books = fread(books, sizeof(struct stock), MAX_BOOKS, fptr);
    fclose (fptr);
    return 0;
}

否则循环并分块读取:

    while (cnt_books = fread(books, sizeof(struct stock), MAX_BOOKS, fptr)) {
      /* ... */
    }

这篇关于从文件读取未知数量的结构-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆