【问题标题】:Read wrong values from binary file从二进制文件中读取错误值
【发布时间】:2014-11-25 17:40:46
【问题描述】:

我想获取一个结构数组,以便按名称对其进行排序并将其写入 txt 文件。但它采用了错误的值,例如奇怪的符号或数字。有谁知道怎么回事?

typedef struct candidato Candidato;

struct candidato {
    char inscr[10];
    char nome[44];
    int periodo;
    int posicao;
    char curso[30];
};

FILE *fp = fopen(filename, "rb");

if (fp == NULL)
{
    fprintf(stderr, "Failed to open file %s for reading\n", filename);
    return ;
}
fseek(fp, 0, SEEK_END);
size_t sz = ftell(fp);
int ncand = sz/sizeof(Candidato);
rewind(fp);
Candidato *arr = malloc(sz);
if (arr == 0)
{
    fprintf(stderr, "Failed to allocate %zu bytes memory\n", sz);
    return ;
}
printf("%d \n",ncand);
int i;
int cont;
for (i = 0; fread(&arr[i], sizeof(Candidato), 1, fp) == 1; i++){
    printf("%s\n",arr[i].nome); //test if it got what I want
}
fclose(fp);

【问题讨论】:

  • 请贴出Candidato的定义。
  • @WeatherVane 你是对的。谢谢。
  • 举一个“错误值”的例子以及它们应该是什么。
  • 发布的定义和值示例
  • 您的文件正确吗?

标签: c arrays struct binaryfiles


【解决方案1】:

我解决了我的问题,这是工作代码:

FILE *f = fopen (filename, "rb");
if(f==NULL){
    printf("Erro na abertura do arquivo. \n");
    system("pause");
    return;
}
fseek(f, 0, SEEK_END);
int  sz = ftell(f);
rewind(f);
Candidato arr[sz/sizeof(Candidato)];
int i;
for (i = 0; fread(&arr[i], sizeof(Candidato), 1, f) == 1; i++) {
    printf("%s %i \n",arr[i].nome,arr[i].inscr);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多