Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can you help me with this small piece of code, thnkx!

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Hi,
ok, here is what I am trying to accomplish here.
I heard that the function Fread(), can automatically read a data block in the size of the structure from the Input file and assigns the data to the appropriate element of the structure. Well that really got me excited, it seem like it can make my work easier.
So Im trying it, but I can't seem to get this piece of code to work. Can you experts take a look at it for me please to see what I am doing wrong? Orbetter yet, if you know another why to do what I wish to accomplish here, please share it with me. And include sample too. Thankx in advance.


#include<iostream>
#include<fstream>
#include<string>
#include<stdio.h>
using namespace std;

struct Book
{ string Isbn;
string Title;
float Price;
int StockAmnt;
};
void main()
{

Book Dat[1];
FILE *Infile; \\This is like ifstream Infile



if((Infile=fopen(&quot;program4.txt&quot;,&quot;rb&quot;))==NULL)
{cout<<&quot;Cant open file&quot;; exit(1);}

if(fread(&Dat,sizeof(Book),4,Infile)!=4)
{ cout<<&quot;Cant read data!&quot;;
}
}

 
The size of the book structure must be fixed length. You are using string types; the size of the string text is unknown.

You'd have better luck using fixed length character arrays instead of strings in this case:

char Isbn[1024];
char Title[1024];

In general you should prefer strings in C++, but in this case the old C string is appropriate.
 
I think that jtm111 is right,
normal C file handling operations will do it for u...
 
The memory &quot;Dat&quot; variable has,is only for one block of book.
But in the function call you are trying to read 4 blocks into it..:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top