Binary I/O in C++ /******************************************************************************
* Random-access file example program in C++.
*
* This shows how to treat a text file as binary and access records within
* it. This reads only the first two records from a 1K block, keeping track
* of where each record starts and ends in the buffer.
*
* Written by John Cole at The University of Texas at Dallas on November 1,
* 2016. Copy, adapt, and use this code freely.
******************************************************************************/

#include "stdafx.h"
#include <stdio.h>
#include <io.h>
#include <iostream>
#include <fstream>

using namespace std;

int main()
 {
 fstream f;

 char buffer[1024];
 int recptr = 0;
 int startptr = 0;
 char record1[100];
 char record2[100];

 // Poor practice here, hard-coding the fully-qualified path of a file.
 f.open("H:\\Classes\\2016Fall\\CS6360Fall2016\\CS6360Asg5TestData.txt", ios::in, ios::binary);
 f.read(buffer, 1024);

 // Find the end of the first record.
 while (buffer[recptr] != '\n')
  recptr++;
 cout << "Record1 is " << recptr << "bytes long" << endl;
 strncpy_s(record1, &buffer[startptr], recptr);
 record1[recptr] = 0; cout << "Record1: " << record1 << endl;

 // Move past the NL character, then save that as the start of the second line.
 recptr++;
 startptr = recptr;
 // Find the end of the second record.
 while (buffer[recptr] != '\n')
  recptr++;
 cout << "Record2 is " << recptr << "bytes long" << endl;
 strncpy_s(record2, &buffer[startptr], recptr-startptr);
 record2[recptr] = 0;
 cout << "Record2: " << record2 << endl;

 system("pause");
 f.close();
 return 0;
 }