Skip to content

Instantly share code, notes, and snippets.

Created November 22, 2015 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/b2e0bf58a4d8ceeb0ca6 to your computer and use it in GitHub Desktop.
Save anonymous/b2e0bf58a4d8ceeb0ca6 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
struct studentInfo
{
char name[20];
int age;
float gpa;
char grade;
};
int main()
{
//Create an array of student info
studentInfo students[4] = {
{ "Ann Annson", 10, 1.10, 'D' },
{ "Bill Billson", 20, 2.20, 'C' },
{ "Carl Carlson", 30, 3.30, 'B' },
{ "Don Donson", 40, 4.00, 'A' },
};
//We need two files, just use fstream since we're inputting and outputting as well
fstream oFile1, oFile2;
//Write array into a text file
oFile1.open("students.txt", ios::out);
for (int i = 0; i < 4; i++)
{
oFile1 << students[i].name << " ";
oFile1 << students[i].age << " ";
oFile1 << students[i].gpa << " ";
oFile1 << students[i].grade << " " << endl;
}
oFile1.close(); //Remember to close it
//Write array into a binary file
oFile2.open("students.bin", ios::out || ios::binary);
oFile2.write(reinterpret_cast<char*>(&students), sizeof(students));
oFile2.close();
//Declare two new arrays; studentsText, studentsBinary
studentInfo studentsText[4], studentsBinary[4];
//Read data from students.txt into studentsText
oFile1.open("students.txt", ios::in);
for (int i = 0; i < 4; i++)
{
oFile1.getline(studentsText[i].name, 20);
oFile1 >> studentsText[i].age;
oFile1 >> studentsText[i].gpa;
oFile1 >> studentsText[i].grade;
oFile1.ignore();
}
oFile1.close(); //Remember to close it
//Display the studentsText array
for (int i = 0; i < 4; i++)
{
cout << studentsText[i].name << " ";
cout << studentsText[i].age << " ";
cout << studentsText[i].gpa << " ";
cout << studentsText[i].grade << " ";
cout << endl;
}
//Get stuff for binary
oFile2.open("students.bin", ios::in | ios::binary);
oFile2.read(reinterpret_cast<char *>(&studentsBinary), sizeof(studentsBinary));
//Display from binary
for (int i = 0; i < 4; i++)
{
cout << studentsBinary[i].name << " ";
cout << studentsBinary[i].age << " ";
cout << studentsBinary[i].gpa << " ";
cout << studentsBinary[i].grade << " ";
cout << endl;
}
oFile2.close();
int student;
studentInfo sTemp;
oFile2.open("students.dat", ios::in | ios::binary);
cout << "Which sudent do you want to see? ";
cin >> student;
oFile2.seekg((student - 1) * sizeof(student), ios::beg);
oFile2.read(reinterpret_cast<char *>(&sTemp), sizeof(sTemp));
cout << sTemp.name << " "
<< sTemp.age << " "
<< sTemp.gpa << " "
<< sTemp.grade << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment