Chiranjibi Adhikari
Chiranjibi Adhikari

Reputation: 29

How to write structure members at once in a file using fwrite() function?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

struct student{
    char *name;
    char *addr;
    int age;
   int clas;
 }*stu;

 int main()
 {
    FILE *fp;
    int choice,another;
    size_t recsize;
    size_t length;

   struct student *stu=(struct student *)malloc(sizeof(struct student));
   stu->name=(char *) malloc(sizeof(char)*20);
   stu->addr=(char*)malloc(sizeof(char)*20);

   recsize=sizeof(*stu);


           fp=fopen("student.txt","a+");
            if(fp==NULL)
               {
                 fp=fopen("student.txt","w+");
                 if(fp==NULL)
                  {
                    printf("cannot open the file");
                    exit(1);
                  }  
                }

                do
                 {
                   fseek(fp,1,SEEK_END);
                   printf("Please Enter student Details\n");

                   printf("Student Name: ");
                   scanf("%s",stu->name);

                    printf("Address: ");
                    scanf("%s",stu->addr);

                    printf("Class: ");
                    scanf("%s",&stu->clas);

                    printf("Age: ");
                    scanf("%s",&stu->age);                     

                    fwrite(stu,recsize,1,fp);

                    printf("Add another Enter 1 ?\n");
                    scanf("%d",&another);
                   }while(another==1);
                  fclose(fp);
        free(stu);


   }

I have code in C which has a structure Student. I am trying to get all structure members values from user. Memory is allocated for structure and two members *name and *addr. when I try to write those values using fwrite() function in a file Student.txt it shows random output ( ཀའ㌱䔀8䵁ཀའ㈱䔀1䵁 ) like this in a file and it is not in readable form. Please provide me the best way to write members of structure in file using fwrite() function.

Upvotes: 1

Views: 886

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You need to use %d instead of %s for ints

printf("Class: ");
scanf("%s",&stu->clas);

printf("Age: ");
scanf("%s",&stu->age);

should be

printf("Class: ");
scanf("%d",&stu->clas);

printf("Age: ");
scanf("%d",&stu->age);

And as pointed out by @David Hoelzer in comments: you're writing the value of the pointers rather than what they contain, change

struct student{
    char *name;
    char *addr;

to

struct student{
    char name[20];
    char addr[20];

and delete those lines:

stu->name=(char *) malloc(sizeof(char)*20);
stu->addr=(char*) malloc(sizeof(char)*20);

Upvotes: 2

Related Questions