簡體   English   中英

從二進制文件讀取錯誤的值

[英]Read wrong values from binary file

我想要一個結構數組,以便可以按名稱對其進行排序並將其寫在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);

我解決了我的問題,這是工作代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM