#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stCrimeArchive {
char id_student[10];
int id_document;
char judgement[30];
int id_crime;
char date[12];
char id_police[12];
};
int main()
{
struct stCrimeArchive *regi;
FILE *filea;
filea = fopen("crimearchives.dat", "r+b");
if(!filea)
filea = fopen("crimearchives.dat", "w+b");
int i;
char num[6];
regi = (struct stCrimeArchive*)malloc (sizeof(struct stCrimeArchive));
printf("ID DOCUMENT: ");
fgets(num, 6, stdin);
regi->id_document= atoi(num);
printf("ID STUDENT: ");
fgets(regi->id_student, 30, stdin);
for(i = strlen(regi->id_student)-1; i && regi->id_student[i] < ' '; i--)
regi->id_student[i] = 0;
printf("CRIME CODE: ");
fgets(num, 6, stdin);
regi->id_crime = atoi(num);
printf("DATE OF THE CRIME: ");
fgets(regi->date, 30, stdin);
for(i = strlen(regi->date)-1; i && regi->date[i] < ' '; i--)
regi->date[i] = 0;
printf("ID POLICE: ");
fgets(regi->id_police, 30, stdin);
for(i = strlen(regi->id_police)-1; i && regi->id_police[i] < ' '; i--)
regi->id_police[i] = 0;
printf("JUDGEMENT: ");
fgets(regi->judgement, 30, stdin);
for(i = strlen(regi->judgement)-1; i && regi->judgement[i] < ' '; i--)
regi->judgement[i] = 0;
fseek(filea, 0, SEEK_END);
fwrite(®i, sizeof(struct stCrimeArchive*), 1, filea);
free(regi);
fclose(filea);
}
上下文如下:我正在制作一个可变长度文件,并在其上使用上面显示的结构编写许多犯罪档案。为此,我需要为所涉及的结构做一个 malloc。问题是当我将它写入文件时,它什么也没写,而且我不知道我在做什么错误。
我也想从同一个文件中读取犯罪档案,但我也不知道我做错了什么。这是我正在尝试做的代码:
int main()
{
struct stCrimeArchive *regi;
regi = (struct stCrimeArchive*)malloc (sizeof(struct stCrimeArchive));
FILE *filea;
filea = fopen("crimearchives.dat", "r+b");
if(!filea)
filea = fopen("crimearchives.dat", "w+b");
rewind(filea);
while (fread(®i, sizeof(struct stCrimeArchive), 1, filea))
printf("%2d %-11s %-11s %8d %-13s %-14s\n", regi->id_document, regi->id_police, regi->date, regi->id_crime, regi->id_student, regi->judgement);
fclose(filea);
}