【发布时间】: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