c - 用 C 从文件中读取其中的所有元素

标签 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 类型的结构对象,存储一些 float 。 注释掉的部分是我在另一个问题中尝试另一种方法,但不理解真正的机制。无论如何,当我调用该函数时,数组是空的。我错了什么?

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

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

最佳答案

编辑:完成功能或多或少类似于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;
    }
}

关于c - 用 C 从文件中读取其中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56740627/

相关文章:

java - 为什么不建议将硬编码的绝对路径名传递给 File 对象构造函数 File(String)

c - 从二进制文件读取 mpq_t

c++ - 内存通过 new[] 泄漏而无需调用 new

r - 读取大量数字时使用 fread(R 中的 data.table)的错误?

c - 打开函数 : how to protect against directory opening?

Python 函数作为 C++ 中的参数

c - malloc 中的内存分配与数组中的内存分配有何不同?

java - 使用桌面的默认应用程序打开存储在 jar 文件中的 PDF 文件

c - C 语言中按颜色解码电阻的程序存在问题

c - 从文件中读取单词并将它们放入数组中