The code given below only displays the char values correctly while int values are garbage values...
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
typedef struct
{
char name[10];
char age[10];
}stu;
void main() {
FILE *fp=fopen("Demo.bin","wb");
FILE *fr=fopen("Demo.bin","rb");
stu *ptr;
int n,i;
printf("\n How many elements???");
scanf("%d",&n);
ptr=(stu *)malloc(sizeof(stu)*n);
i=0;
while(i<n)
{
scanf("%s%d",ptr->name,ptr->age);
fseek(fp,sizeof(ptr)*i,SEEK_SET);
fwrite(ptr,sizeof(ptr),1,fp);
i++;
}
fclose(fp);
i=0;
while(i<n)
{
fseek(fr,sizeof(ptr)*i,SEEK_SET);
fread(ptr,sizeof(ptr),1,fr);
printf("%s%d",ptr->name,ptr->age);
i++;
}
free(ptr);
fclose(fr);
getch();
}
The code generates an output with correct string value but garbage integer value.
You cannot call %d
on a character array. You must first convert the char array to a integer, or you can just print it as a string with %s
just like you did for the person's name.