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;
 }

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*.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.