0

I'm supposed to write a tcp server program which writes into a file a record as structure.
The code is given below:

int n,i;
 cout<<"Enter number of student records";
 cin>>n;
 for(i=0;i<n;i++)
 {
  cout<<"Enter id,name,average mark";
  cin>>r[i].id>>r[i].name>>r[i].mark;
 }
int i,n1;
 FILE *fp;
 FILE *file = fopen("db.dat", "wb"); 
 cout<<"Writing into file\n";
 if ( file != NULL )
 { 
  for(i=0;i<n;i++)
	 fwrite(&r[i], sizeof r[i], 1, file); 
  fclose(file);
 }
 cout<<"Writing completed\n";

There is no problem in writing part(or there is????)
When i read from the file using fread it prints junk values. What is the problem??
Does fread not place correct values in respective variables? If not how to do it??

struct rec re;
fread(&re,sizeof re,1,fp);
 for(i=0;i<n;i++)
 {
  fread(&re,sizeof re,1,fp);
  cout<<re.id<<re.name<<re.mark;
 }
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

If the following doesn't fix the problem then the problem is in the way the data is being input as posted in your first code snippet.

int i,n1;
FILE *file = fopen("db.dat", "wb"); 
cout<<"Writing into file\n";
if ( file != NULL )
{ 
    fwrite(r, sizeof(r[0]), n,file); 
    fclose(file);
}
cout<<"Writing completed\n";

and

struct rec re;
FILE *file = fopen("db.dat", "rb"); 
while( fread(&re,sizeof re,1, file) > 0)
{
  cout<<re.id<<re.name<<re.mark<<'\n';
}

Since this is a c++ program you really should use ofstream and ifstream classes instead of FILE*.

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.