How to write structure record into file using fwrite() function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shivapadma
    New Member
    • Mar 2007
    • 40

    How to write structure record into file using fwrite() function?

    1.i am just trying to insert a "structure record" into a file using fwrite() function by the following code

    2.
    #include<stdio. h>
    #include<conio. h>
    struct student
    {
    char name[20];
    int rollno;
    };
    void main()
    {
    FILE *fp1;
    struct student s1={"",0};
    clrscr();
    printf("enter the details\n");
    scanf("%s %d",s1.name,&s1 .rollno);
    printf("%d\n",s 1.rollno);
    fp1=fopen("empd et.txt","w");
    fwrite( &s1,sizeof( struct student ),1,fp1 );
    printf("the record is entered");
    fclose(fp1);
    getch();

    }

    3.when i executed the above program,it just inserting only the "name" field and
    the "rollno" field with some garbage

    4.please,someon e help me....
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The rollno member of the struct is an int but the file is a text file.

    Convert the int to a string and write the string.

    Or open the file as a binary file but don't expect to view the contents with a text editor.

    Comment

    • shivapadma
      New Member
      • Mar 2007
      • 40

      #3
      yes,i have converted the rollno(int) into string

      now i am able to insert both name and rollno.

      thanks....

      Comment

      Working...