1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include "ConsoleApplication36.h"
using namespace std;
// define structure studentInfo
struct studentInfo
{
char name[20];
int age;
float gpa;
char grade;
};
int main()
{
//create array of structures
studentInfo student[4] =
{ { "Ann Annson", 10, 1.10, 'D' },
{ "Bill Billson", 20, 2.20, 'C'},
{ "Carl Carlson", 30, 3.30, 'B'},
{"Don Donson", 40, 4.40, 'A' } };
// Create fstream file.
fstream dataFile;
// Open fstream file in out mode.
dataFile.open("students.txt", ios::out);
// Write array to text file.
for (int i = 0; i < 4; i++)
{
dataFile << student[i].name << "\n"; //writing line 1, name
dataFile << student[i].age << "\n"; // writing line 2, age
dataFile << student[i].gpa << "\n"; // line 3, gpa
dataFile << student[i].grade << "\n"; // line 4, grade
}
dataFile.close();
// Write the array of structures to binary file.
dataFile.open("students.bin", ios::out | ios::binary);
dataFile.write(reinterpret_cast<char *>(&student), sizeof(student));
dataFile.close();
// Declare two more arrays of structures for reading from files.
studentInfo studentsText[4];
studentInfo studentsBinary[4];
// Read text file to the array, studentsText
dataFile.open("students.txt", ios::in);
int i = 0;
while (dataFile)
{
dataFile.getline(studentsText[i].name, 20);
dataFile >> studentsText[i].age;
dataFile >> studentsText[i].gpa;
dataFile >> studentsText[i].grade;
if (dataFile) // increment count only if file access was successful
i++;
dataFile.ignore(); // remove trailing newline
}
// read the binary file to studentsBinary array of structures.
dataFile.open("students.bin", ios::in | ios::binary);
dataFile.read(reinterpret_cast<char *>(&studentsBinary), sizeof(studentsBinary));
dataFile.close();
// Output studentsText.
cout << "Students Text" << endl;
cout << "-------------" << endl;
for (int i = 0; i < 4; i++)
{
cout << studentsText[i].name << endl;
cout << studentsText[i].age << endl;
cout << studentsText[i].gpa << endl;
cout << studentsText[i].grade << endl;
}
// Output studentsBinary.
cout << "Students Binary" << endl;
cout << "---------------" << endl;
for (int i = 0; i < 4; i++)
{
cout << studentsBinary[i].name << endl;
cout << studentsBinary[i].age << endl;
cout << studentsBinary[i].gpa << endl;
cout << studentsBinary[i].grade << endl;
}
return 0;
}
| |