Example 3-3 - binary file I/O : a practical example

This example demonstrates reading text file, storing each record in a struct and writing it out as a binary file.  The”processing” requirement is to read the binary file and give all teachers a 5% raise and give Joe Bentley a 10% raise.  The binary file will be updated to reflect the changes.

Input Text File

AGUILAR,  RICARDO L    ANIMAL CONTROL OFFICER                 70644.00
ALLISON,  JOHN L       ANIMAL TEACHERCONTROL OFFICER          64392.00
AYALA,  ARTHUR         ANIMAL CONTROL OFFICER                 70644.00
BATINICH,  JACLYN M    VETERINARY ASST                        66948.00
BENTLEY, JOE           TEACHER                                95000.00
CABALLERO,  JORGE      ANIMAL CONTROL OFFICER                 45924.00
CRAYTON,  MARSTINE L   SUPVSR OF ANIMAL CONTROL OFFICERS      73992.00
DEL RIO,  JOSE A       SUPVSR OF ANIMAL CONTROL OFFICERS      89124.00

ex3-3.cpp
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <fstream>
  4. #include <cstdlib>
  5. #include <cstring>
  6. using namespace std;
  7.  
  8. const int NumRecords = 27;
  9. const int SizeOfName = 23;
  10. const int SizeOfJobtitle = 39;
  11.  
  12. struct SalaryData {
  13.     char name[SizeOfName];
  14.     char jobtitle[SizeOfJobtitle];
  15.     float salary;
  16. };
  17.  
  18. void printSalaryData(const SalaryData& record);
  19. void rtrim(char* text);
  20. void readAndPrintBinaryFile(const char* binaryfilename);
  21. void processBinaryFile(const char* binaryfilename);
  22. void readTextFileAndWriteToBinaryFile(const char* textfilename, const char* binaryfilename);
  23.  
  24. int main()
  25. {
  26.     const char* textfilename = "c:/temp/ex3data.txt";
  27.     const char* binaryfilename = "c:/temp/ex3data.bin";
  28.     readTextFileAndWriteToBinaryFile(textfilename, binaryfilename);
  29.     processBinaryFile(binaryfilename);
  30.     readAndPrintBinaryFile(binaryfilename);
  31. }
  32.  
  33. void readTextFileAndWriteToBinaryFile(const char* textfilename, const char* binaryfilename)
  34. {
  35.     ifstream fin(textfilename);
  36.     if (!fin)
  37.     {
  38.         cerr << "Unable to open input text file " << textfilename
  39.              << endl;
  40.         exit(1);
  41.     }
  42.     ofstream fout(binaryfilename, ios::binary);
  43.     if (!fout)
  44.     {
  45.         cerr << "Unable to open input text file " << textfilename
  46.              << endl;
  47.         exit(2);
  48.     }
  49.  
  50.     char buffer[80];
  51.     SalaryData temp;
  52.  
  53.     for (int i = 0; i < NumRecords; ++i)
  54.     {
  55.         fin.getline(buffer, sizeof (buffer));
  56.         strtok(buffer, "\r");
  57.         strncpy(temp.name, buffer, SizeOfName);
  58.         temp.name[SizeOfName - 1] = 0;
  59.         rtrim(temp.name);
  60.         strncpy(temp.jobtitle, buffer + 23, SizeOfJobtitle);
  61.         temp.jobtitle[SizeOfJobtitle - 1] = 0;
  62.         rtrim(temp.jobtitle);
  63.         temp.salary = atof(buffer + 61);
  64.         printSalaryData(temp);
  65.         fout.write(reinterpret_cast<const char*>(&temp),
  66.                    sizeof (SalaryData));
  67.     }
  68.     cout << "--------------------------------------------------\n";
  69. }
  70.  
  71. void printSalaryData(const SalaryData& record)
  72. {
  73.     cout << fixed << setprecision(2);
  74.     cout << left << setw(SizeOfName + 1) << record.name
  75.             << setw(SizeOfJobtitle + 1) << record.jobtitle
  76.             << right << setw(10) << record.salary << endl;
  77. }
  78.  
  79. void rtrim(char* text)
  80. {
  81.     size_t size = strlen(text);
  82.     for (int i = size - 1; i > 1; --i)
  83.     {
  84.         if (!isspace(text[i])) break;
  85.         else text[i] = 0;
  86.     }
  87. }
  88.  
  89. void readAndPrintBinaryFile(const char* binaryfilename)
  90. {
  91.     ifstream fin(binaryfilename, ios::binary | ios::in);
  92.     SalaryData temp;
  93.     if (fin)
  94.     {
  95.         for (int i = 0; i < NumRecords; ++i)
  96.         {
  97.             fin.read(reinterpret_cast<char*>(&temp),
  98.                      sizeof (temp));
  99.             printSalaryData(temp);
  100.         }
  101.     }
  102.     else
  103.     {
  104.         cerr << "Unable to open binary input file "
  105.              << binaryfilename << endl;
  106.         exit(3);
  107.     }
  108. }
  109.  
  110. // Teachers get a 5% raise
  111. // Joe Bentley gets a 10% raise
  112. void processBinaryFile(const char* binaryfilename)
  113. {
  114.     // open the binary file for read and write
  115.     fstream finfout(binaryfilename, ios::binary|ios::in|ios::out);
  116.     SalaryData temp;
  117.     if (finfout)
  118.     {
  119.         while (!finfout.eof())
  120.         {
  121.             finfout.read(reinterpret_cast<char*>(&temp),
  122.                          sizeof (temp));
  123.             if (strstr(temp.name, "BENTLEY"))
  124.             {
  125.                 temp.salary *= 1.1;
  126.                 // Backup and rewrite the record
  127.                 finfout.seekp(finfout.tellg() –
  128.                     static_cast<streampos>(sizeof (SalaryData)));
  129.                 finfout.write(reinterpret_cast<char*>(&temp),
  130.                               sizeof (temp));
  131.             }
  132.             else if (!strcmp(temp.jobtitle, "TEACHER"))
  133.             {
  134.                 temp.salary *= 1.05;
  135.                 // Backup and rewrite the record
  136.                 finfout.seekp(finfout.tellg() –
  137.                     static_cast<streampos> (sizeof (SalaryData)));
  138.                 finfout.write(reinterpret_cast<char*>(&temp),
  139.                               sizeof (temp));
  140.             }
  141.             else
  142.             {
  143.             }
  144.         }
  145.     }
  146.     else
  147.     {
  148.         cerr << "Unable to binary file for processing "
  149.              << binaryfilename << endl;
  150.         exit(4);
  151.     }
  152.     if (!finfout.good()) finfout.clear();
  153.     finfout.close();
  154. }

Output

AGUILAR,  RICARDO L     ANIMAL CONTROL OFFICER                    70644.00
ALLISON,  JOHN L        ANIMAL TEACHERCONTROL OFFICER             64392.00
AYALA,  ARTHUR          ANIMAL CONTROL OFFICER                    70644.00
BATINICH,  JACLYN M     VETERINARY ASST                           66948.00
BENTLEY, JOE            TEACHER                                   95000.00
CABALLERO,  JORGE       ANIMAL CONTROL OFFICER                    45924.00
CRAYTON,  MARSTINE L    SUPVSR OF ANIMAL CONTROL OFFICERS         73992.00
DEL RIO,  JOSE A        SUPVSR OF ANIMAL CONTROL OFFICERS         89124.00
DIAKHATE,  MAMADOU      OPERATIONS MANAGER - ANIMAL CONTROL       85008.00
DRAKE,  TAURUS L        ANIMAL CONTROL INSPECTOR                  70644.00
EDGECOMBE,  CHERYL K    ANIMAL CONTROL INSPECTOR                  58644.00
FELTON,  DONIELLA M     TEACHER                                   47844.00
FRANCO,  ARTURO         ANIMAL CONTROL OFFICER                    45924.00
GARNER,  LINDSAY        VETERINARIAN                              88080.00
HAMILTON,  ARTHUR       ANIMAL SHELTER MANAGER                    68220.00
HOLCOMB,  ALLEN R       ANIMAL CONTROL INSPECTOR                  77520.00
HOWARD,  MARYANN J      ANIMAL CONTROL INSPECTOR                  64392.00
HUBBS,  CARLA A         SUPERVISING VETERINARY TECHNICIAN         62820.00
JACOB,  VIVISH          SUPVSR OF ANIMAL CARE AIDES               84420.00
KELLER,  AUDREY A       VETERINARIAN                             124428.00
LOZANO,  RENE P         ANIMAL CONTROL OFFICER                    67464.00
MARTINIS,  JENNIFER     ANIMAL CONTROL OFFICER                    41832.00
RUSSELL,  SUSAN J       TEACHER                                  130008.00
SCHLUETER,  JENNIFER L  EXEC ADMINISTRATIVE ASST II               59976.00
SILVA,  YVONNE          ANIMAL CONTROL OFFICER                    41832.00
WALTERS,  MICHELLE      TEACHER                                   70092.00
YAMAJI,  PETER S        VETERINARIAN                             128136.00
---------------------------------------------------------------
AGUILAR,  RICARDO L     ANIMAL CONTROL OFFICER                    70644.00
ALLISON,  JOHN L        ANIMAL TEACHERCONTROL OFFICER             64392.00
AYALA,  ARTHUR          ANIMAL CONTROL OFFICER                    70644.00
BATINICH,  JACLYN M     VETERINARY ASST                           66948.00
BENTLEY, JOE            TEACHER                                  104500.00
CABALLERO,  JORGE       ANIMAL CONTROL OFFICER                    45924.00
CRAYTON,  MARSTINE L    SUPVSR OF ANIMAL CONTROL OFFICERS         73992.00
DEL RIO,  JOSE A        SUPVSR OF ANIMAL CONTROL OFFICERS         89124.00
DIAKHATE,  MAMADOU      OPERATIONS MANAGER - ANIMAL CONTROL       85008.00
DRAKE,  TAURUS L        ANIMAL CONTROL INSPECTOR                  70644.00
EDGECOMBE,  CHERYL K    ANIMAL CONTROL INSPECTOR                  58644.00
FELTON,  DONIELLA M     TEACHER                                   50236.20
FRANCO,  ARTURO         ANIMAL CONTROL OFFICER                    45924.00
GARNER,  LINDSAY        VETERINARIAN                              88080.00
HAMILTON,  ARTHUR       ANIMAL SHELTER MANAGER                    68220.00
HOLCOMB,  ALLEN R       ANIMAL CONTROL INSPECTOR                  77520.00
HOWARD,  MARYANN J      ANIMAL CONTROL INSPECTOR                  64392.00
HUBBS,  CARLA A         SUPERVISING VETERINARY TECHNICIAN         62820.00
JACOB,  VIVISH          SUPVSR OF ANIMAL CARE AIDES               84420.00
KELLER,  AUDREY A       VETERINARIAN                             124428.00
LOZANO,  RENE P         ANIMAL CONTROL OFFICER                    67464.00
MARTINIS,  JENNIFER     ANIMAL CONTROL OFFICER                    41832.00
RUSSELL,  SUSAN J       TEACHER                                  136508.41
SCHLUETER,  JENNIFER L  EXEC ADMINISTRATIVE ASST II               59976.00
SILVA,  YVONNE          ANIMAL CONTROL OFFICER                    41832.00
WALTERS,  MICHELLE      TEACHER                                   73596.60
YAMAJI,  PETER S        VETERINARIAN                             128136.00