我想获取一个结构数组,以便我可以按名称对其进行排序并将其写入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);
答案 0 :(得分:0)
我解决了我的问题,这是工作代码:
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);
}