从文件中读取C中的所有元素

时间:2019-06-24 16:28:35

标签: c file fread realloc

所以我需要编写一个函数来读取位文件中的所有元素。关键是我不知道内部可能有多少个元素,但是我知道元素的类型。因此,我尝试编写此函数:

   void loadData(Parallelogram **array) {
            FILE *data; long size;
            //int numberOfElements = 0;
            int numberOfObjects = 0;


            if ((data = fopen(name, "rb"))!=NULL) {


                fseek(data, 0, SEEK_END);
                size = ftell(data);
                fseek(data, 0, SEEK_SET);


                if (size<(long)sizeof(Parallelogram)) {

                    printf("The file is empty try to open another file maybe");

                } else {

                    Parallelogram *tempArray;

                    numberOfObjects = size/sizeof(Parallelogram);

                    tempArray = realloc(*array, numberOfObjects*sizeof(Parallelogram));

                    if (tempArray==NULL) {
                         printf("There was an error reallocating memory");
                    } else { *array = tempArray; }

                    fread(*array, sizeof(Parallelogram), numberOfObjects, data);

                }
            }
            fclose(data);
        }

元素是Parallelogram类型的结构对象,存储一些浮点数。 被注释掉的部分是我尝试从另一个问题中尝试另一种方法,但不了解真正的机制。无论如何,当我调用函数时,数组为空。我怎么了?

编辑:根据要求,这是主要函数,我在其中调用函数loadData()

int main() {
    Parallelogram *paraArray = NULL;
    loadData(&paraArray);
}

1 个答案:

答案 0 :(得分:1)

编辑:与OP完全相同的功能。

您可以执行以下操作:

void loadData(Parallelogram **array, size_t * n) {
    FILE *data;

    if ((data = fopen("file.bin", "rb"))!=NULL) {
        Parallelogram buffer[100]; // may be malloc'd
        size_t chunk_size = 100;
        size_t read_size = 0;
        size_t number_of_objects = 0;
        Parallelogram *aux = NULL;
        *array = NULL;

        while ((read_size = fread(buffer, sizeof *buffer, chunk_size, data)) > 0) {
            aux = realloc(*array, (number_of_objects + read_size) * sizeof *buffer);
            if (aux == NULL) {
                // ERROR
                free(*array);
                // clean, break/exit
            }
            *array = aux;
            memcpy(*array + number_of_objects, buffer, read_size*sizeof *buffer);
            number_of_objects += read_size;
        }
        // check file for errors (ferror()) before exit
        fclose(data);
        *n = number_of_objects;
    }
}