user3230962
user3230962

Reputation: 9

Cannot store integer value in a data file in C using structure

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.

Upvotes: 0

Views: 749

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>
#include <stdlib.h> //!
#include <conio.h>

typedef struct {
    char name[10];
    int age; //!
} stu;

int main(){ //!
    FILE *fp=fopen("Demo.bin","wb");
    FILE *fr; //!
    stu *ptr;
    int n,i;

    printf("\n How many elements???");
    scanf("%d", &n);
    ptr=malloc(sizeof(stu)*n);
    i=0;
    while(i<n){
        scanf("%s %d", ptr[i].name, &ptr[i].age); //!
        fwrite(&ptr[i++], sizeof(*ptr), 1, fp); //!
    }
    fclose(fp);
    //memset(ptr, 0, n*sizeof(*ptr)); //!
    free(ptr); //!
    ptr=malloc(sizeof(stu)*n); //!
    fr=fopen("Demo.bin","rb"); //!
    i=0;
    while(i<n){
        fread(&ptr[i], sizeof(*ptr), 1, fr); //!
        printf("%s %d\n", ptr[i].name, ptr[i].age); //!
        ++i;
    }
    free(ptr);
    fclose(fr);
    getch();
    return 0;
}

Upvotes: 0

sujin
sujin

Reputation: 2853

Your code reading integer in chararter array. Your compiler probably gives warning.

Same like sample code below.

#include <stdio.h>
int main()
{
    char age[10];
    scanf("%d", age);
    printf("out : %d\n", age);
}

After compilation :

warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘char *’ [-Wformat]
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat]

OUTPUT:

23
out : -1073788814

So change your char age[10] to int age your code will work.

typedef struct
{
      char name[10];
      int age;
}stu;

Upvotes: 0

George
George

Reputation: 416

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.

Upvotes: 1

Related Questions