#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);
}
The context is the following: I am making a variable length file, and on it i’m writing many crime archive with the struct shown above. To do it i need to do a malloc for the struct involved. The problem is when I write it to file, it doesn’t write anything, and I don’t know what mistake(s) I’m doing.
Also I want to read the crime archives from the same file, but I also don’t know what I am doing wrong. Here’s the code for what I am trying to do:
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);
}
You’ll want to write the size of the struct and not the size of the pointer to the struct.
Or maybe this would be more clear: