c++ - 读取二进制结构数据

标签 c++ c structure

我已经编写了代码,但无法找出错误的解决方案。我认为这是非常简单的修复。

我有3个文件

grades.txt // contains 8 grades
grades.h // structure
grades.c // main

这里是所询问的程序的描述

  1. 接受两个参数,1 表示文件名 Grades.txt,1 表示用户 ID(例如 123)
  2. 显示成绩和平均成绩,直到我获得全部 8 个成绩或达到负成绩
  3. 将用户 ID 转换为数字 uid
  4. 从偏移量 (uid*sizeof(struct GR)) 开始读取结构体

成绩.h

#ifndef GRADE
#define GRADE
struct GR {
    float gr[8];
};
#endif

成绩.c

#include <stdio.h>
#include "grades.h"
int main(int argc, char *argv[]) {    
    struct GR *grades = melloc(sizeof(struct GR));
    FILE *file = fopen(argv[1], "rb");    

    // convert character uid into integer uid
    char *chUid = argv[2];
    int uid = 0;
    int len = strlen(chUid);
    for (int i = 0; i < len; i++) {
        uid = uid * 10 + (chUid[i] - '0');
    }
    printf("Converted uid: %d \n", uid);

    fread(grades, uid * sizeof(struct GR), 1, file);

    float total = 0, avg = 0;
    int i = 0;
    while (i < 9 && grades->gr[i] > 0) {
        printf("%d\n", grades->gr[i]);
        total += grades->gr[i];
        i++;
    }
    printf("Average: %d \n", total / i);        
    return 0;
}

我的错误消息是

错误LNK2019:函数_main中引用了无法解析的外部符号_melloc
错误 LNK1120:1 个未解析的外部

----更新------

我添加了 header 并更改了 melloc 和 malloc 中的拼写错误,错误消失了,但我陷入了 fread 方法..结构没有任何值

最佳答案

你已经

error LNK2019: unresolved external symbol _melloc referenced in function _main

因为在 C 中分配内存的函数称为 malloc 而不是 melloc (也许是瓜;p):

void* malloc (size_t size);

您必须包含一个声明 malloc 的 header :

#include <stdlib.h>

关于c++ - 读取二进制结构数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319565/

相关文章:

c - 将数据存储在数组中并循环,1个元素为空

c - 使用 Structure 的数组进行排序

c - 限制结构体中的指针

c++ - 删除指针时程序崩溃

c++ - MSVCP110.dll 丢失

c - 在 C 中为自引用结构分配内存

c - 将 int 转换为 void* 或相反是什么意思?

c++ - 如何将 std::vector<Eigen::vectorXd> 中的 vector 复制到另一个 std::vector<Eigen::vectorXd> 中的另一个 vector

c++ - 计算圆上的所有点

C - 高阶函数