Reading from a file all elements within it in C

岁酱吖の 提交于 2019-12-11 14:38:11

问题


So I need to write a function that reads all the elements inside a bit file. The point is that I don't know how many elements there could be inside, but I know what type of elements are. So I tried to write this function:

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

The elements are struct objects of type Parallelogram, storing a few floats. The commented out part was me trying another method form another question but not understanding the real mechanism. Anyways when I call the function the array is empty. What am I getting wrong?

EDIT: As requested this is the main function where I call the function loadData()

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

回答1:


EDIT: complete function more or less like the OP's.

You may do something like:

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


来源:https://stackoverflow.com/questions/56740627/reading-from-a-file-all-elements-within-it-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!