繁体   English   中英

如何在C中存储从文件读取的结构?

[英]How do I store structures that are read from a file in C?

我想出了一个学习C语言的项目,但是我碰到了很多困难。 该项目只是一个纸牌游戏,玩家拥有两套纸牌,一套是一定尺寸的套牌,另一套是他们收集的纸牌,数量可以根据需要而定。 卡结构如下:

struct card {   
    char name[256];
    char special[256];
    char type[100];
    char rarity[100];
    int points;
};

然后,我有一个名为coll.txt的集合文件。

first card goes here 50
second card goes here 70
...

然后,我有一个(草率)函数,该函数从文件读取并将其存储到临时卡中:

void read_into_collection(FILE *f) {
    char *file_text;
    char *token;
    int i;
    struct card temp;

    file_text = (char *) malloc(sizeof(struct card));

    while(fgets(file_text, sizeof(struct card), f)) {
        for(i = 1, token = strtok(file_text, " "); token; i++, token = strtok(NULL, " ")) {
            switch (i) {
            case 1:
                strcpy(temp.name, token);
                break;
            case 2:
                strcpy(temp.special, token);
                break;
            case 3:
                strcpy(temp.type, token);
                break;
            case 4:
                strcpy(temp.rarity, token);
                break;
            case 5:
                temp.points = atoi(token);
                break;
            default:

                i = 0;
                break;
            }
        }
    }


    free(file_text);
}

因此,当i = 6我准备将临时卡移到集合中,并将下一张卡读入temp变量,依此类推。 但是我该怎么做呢? 我在弄清楚实际应该收集什么时遇到了麻烦。 起初我以为:

struct card *collection = (struct card *) malloc(number_of_cards * sizeof(struct card));

但是,如果我是对的,则malloc()返回指向大块内存的指针,并且该内存不是像数组那样顺序的,因此我无法递增该指针来存储卡。

我还尝试计算文件中的行数(每行是一张卡),然后制作该大小的数组,但是我得到一个错误,指出该值不是常数。

将这些卡存储为收藏的最佳方法是什么? 我只是将集合做成一个很大的数组,但是我觉得这种情况经常出现在项目中,宁愿学习如何处理它,也不要轻易走开。

但是,如果我是对的,则malloc()返回指向大块内存的指针,并且该内存不是像数组那样顺序的,因此我无法递增该指针来存储卡。

假。 它是顺序的。 您可以使用malloc()创建任何数组:

mystruct* ptr = (mystruct*) malloc(sizeof(mystruct) * numberOfStructs)

for(int i = 0; i < numberOfStructs, i++) {
    ptr[i].setSomeInfo(x);
}

这是用C语言完成的标准方法。

我以前经常用C编程,这是我的最爱之一。 这是我的答案。

您使用malloc的方式确实分配了一个数组

struct card *collection = (struct card *) malloc(number_of_cards * sizeof(struct card));

每次对malloc的调用都会返回一个指向内存中不同区域的指针。 但是,一次调用malloc总是返回一个连续的块。

如果知道卡数,则可以使用它来分配一个数组,然后像这样访问它

//added some code to prevent overflow
collection[i].name[255] = 0;
strncpy(collection[i] .name, token, 255);

如果卡数未知,该怎么办。 然后做一个链表。 这是链表的主要用途,用于存储大小未知的集合的内容。

暂无
暂无

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

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