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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please help a student!

Status
Not open for further replies.

Valistar

Programmer
Aug 29, 2002
1
AU
I am learning C++ and it's giving me problems :(

For one of my assignments I need to input data from a binary file containing structs that the user inputs info to.

I can create the file no worries it when i try to read them back from the file into the program that I have problems. I am supposed to be randomly accessing the file (no sequential searches) based on input from the user, then displaying the info to the user.
If anyone can help I would really appreciate it.

Help me [insert name] youre my only hope!!
 
Hi,

the fastets way to access bynary data from file is
to use the same structure type from routines that writes
and reads data. For this purpose you have to write 2 routines (or 2 programs: 1 writes , 1 reads ).

mystruct.h
----------
stuct mystruct {
char c;
int i ; }

write.c
-------
#include "mystruc.h"
FILE *stream;
struct mystruct s ;
s.c='A';
s.i=0;
.....
stream=fopen( "myfile.dat", "w+b" ) ; // see doc about +b
fwrite( &s, sizeof(s), 1, stream ) ;
fclose(stream);

read.c
-------
#include "mystruc.h"
FILE *stream;
struct mystruct s ;
.....

stream=fopen( "myfile.dat", "r+b" ) ; // see doc about +b
fread( &s, sizeof(s), 1, stream ) ;
fclose(stream);

printf( "%c %d\n", s.c, s.i ) ;

******* *******

Using this method is very fast, by I suggest another way.
I work with programs from more that 20 years: this method is
fast but you have to manage 2 programs and to see data on
file, you need a your-written program: during debug you don't know if the error is in the program 1 or 2.

Using text file, for store data, is longer: to save
data you have to use printf and scanf to retrieve.
But you can print file.dat directly or consult it
by an editor: if you are the alone user, you can
omit to write the writing program: you can use text-editor.

If you, however, intend to use binary file warning to a thing: the compiler may put the fileds not near each to other; to optimize int access, it can leave 1 or 3 bytes
between c and i (see mystruct); if you use the same compiler
and CPU to build write and read there are no problem.
Put attention ti the file size: it can be 3 bytes long
4 or 8, depending size of int and the type of alligment.

bye.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top