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

read binary file

Status
Not open for further replies.

earlrainer

Programmer
Mar 1, 2002
170
IN
Hi ,

i am not very familiar with c++.

please help me how to read a binary file

someone gave me a binary file which i have to read

the record in the binay file has this structure
Name string(13)
age string(2)
salary string(6)

how can i read this in C++

Thanks
 
Try this (which is C as well as C++):
Code:
#include <stdio.h>
#include <memory.h>
#include <string.h>

static nRec = 0;

void processRec(
   char* aRec
) {
   /* gets the bits of the record and prints them */
   char name[13 + 1] = &quot;&quot;;
   char age[2 + 1] = &quot;&quot;;
   char salary[6 + 1] = &quot;&quot;;
   memmove(name, aRec, 13);
   memmove(age, aRec + 13, 2);
   memmove(salary, aRec + 15, 6);
   ++nRec;
   printf(
         &quot;Record %d: name=\&quot;%s\&quot;; age=\&quot;%s\&quot; salary=\&quot;%s\&quot;\n&quot;
      ,  name, age, salary
   );
   return;
}

int main() {
   /* open a file in binary mode for reading */
   FILE* fIn = fopen(&quot;myfile.dat&quot;, &quot;rb&quot;);
   char rec[21];
   if (fIn == (FILE*) 0) {
      /* file not openend */
      printf(&quot;Cannot find file.\n&quot;);
   } else {
      /*
         reads each record of 21 characters and processes it
         fread() returns a value less than 21 when the last
         record is read
      */
      while (fread(rec, sizeof(char), 21, fIn) == 21) {
         processRec(rec);
      }
      fclose(fIn);
   }
   return 0;
}
Hope this helps.


________________________________________
[hippy]Roger J Coult; Grimsby, UK
In the game of life the dice have an odd number of sides.
 
Whoops! missed something out:
[tt]
printf(
&quot;Record %d: name=\&quot;%s\&quot;; age=\&quot;%s\&quot; salary=\&quot;%s\&quot;\n&quot;
, name, age, salary
);
[/tt]

should be:
[tt]
printf(
&quot;Record %d: name=\&quot;%s\&quot;; age=\&quot;%s\&quot; salary=\&quot;%s\&quot;\n&quot;
, nRec, name, age, salary
);
[/tt]





________________________________________
[hippy]Roger J Coult; Grimsby, UK
In the game of life the dice have an odd number of sides.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top