writing structure to a file

P

prashant.khade1623

Hi

I am trying ti write a structure to a file, but I am getting
segmentation fault. Below is my program

#include<stdio.h>
main()
{
FILE *fp;
struct student {
int age;
char name[19];
char school[15];
};

struct student s1={25,"khade","KVOFPM"};
struct student s2={25,"khade","KVOFPM"};

fp = fopen("khade","r+");

fwrite(&s1,sizeof(struct student ),1,fp);
fwrite(&s2,sizeof(struct student ),1,fp);


}


Can you tell me why I am getting the error.
Also I want to read from the file. how can I do that ?

Thanks in advance
 
P

Pradeep

Hi
In your program
file is opening in 'r+' mode
'r+' opens the file for both reading and writing.
but it won't check whether file is there or not.
(i.e., it won't create new file)
in that case you need to create the file in 'w' mode
that will solve your problem.
or if you don't want to change your code, then you need to create a
blank file in the current directory with the same name you are opening
the file in 'r+' mode(crete a file blank file "khade" in the current
directory) then your code should work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top