954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Reading from binary File using fread prints junk message.

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;
 }
hari.sarvothama
Newbie Poster
17 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
 

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

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: