0% found this document useful (0 votes)
2 views

FileExample6

The document is a C++ program that allows users to write and read student data, including name and grade, to and from a binary file. It defines a 'student' structure and provides functions to handle file operations. The program prompts the user for input to either write a new student record or read an existing one from a specified file.

Uploaded by

phanx549
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

FileExample6

The document is a C++ program that allows users to write and read student data, including name and grade, to and from a binary file. It defines a 'student' structure and provides functions to handle file operations. The program prompts the user for input to either write a new student record or read an existing one from a specified file.

Uploaded by

phanx549
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <string>
#include <fstream>

using namespace std;

const int NAME_SIZE = 20;

struct student {
float grade;
char * name;
};

void writeFile(fstream & fs, string fn) {


student s;

fs.open(fn, ios::out | ios::binary);

if (fs) {
s.name = new char [NAME_SIZE];

cout << "Name: ";


cin.getline(s.name, NAME_SIZE);
cout << "Grade: ";
cin >> s.grade;
cin.ignore();

fs.write(reinterpret_cast<char *> (&s), sizeof(s));

delete [] s.name;

fs.close();
}
else {
cout << fn << " could not be opened" << endl;
exit(EXIT_FAILURE);
}
}

void readFile(fstream & fs, string fn) {


student s;

fs.open(fn, ios::in | ios::binary);


if (fs) {
fs.read(reinterpret_cast<char *> (&s), sizeof(s));

cout << "Name: " << s.name << endl;


cout << "Grade: " << s.grade << endl;

fs.close();
}
else {
cout << fn << " could not be opened" << endl;
exit(EXIT_FAILURE);
}
}

int main() {
fstream fs;
string filename;
int choice;

cout << "Enter 1 to write, 2 to read: ";


cin >> choice;
cin.ignore();

cout << "Input the file name to work with: ";


getline(cin, filename);

if (choice == 1)
writeFile(fs, filename);
else
readFile(fs, filename);

return 0;
}

You might also like