Create Student Record File in C++.
Write a C++ program to create student record file. The program will input and write records in file. It will ask “Do you want to add more records (y/n)? If the user enters a ‘y’ , the program will input one more record otherwise it will stop.
Source Code
#include <iostream> #include <fstream> using namespace std; // Define the structure struct Student { int rno; char name[30]; int marks; }; int main() { Student srec; // Create a binary file for writing fstream file1("d://file.dat", ios::binary | ios::app); if (!file1) { cout << "Error: Unable to open file." << endl; return 1; } char choice = 'y'; while (choice == 'y') { // Input student record cout << "Enter Roll Number: "; cin >> srec.rno; cin.ignore(); // Ignore newline character left in the input buffer cout << "Enter Name: "; cin.getline(srec.name, 30); cout << "Enter Marks: "; cin >> srec.marks; // Write the record into the file file1.write((char*)&srec, sizeof(srec)); cout << "Do you want to add more records? (y/n): "; cin >> choice; } // Close the file file1.close(); return 0; }
Output:
Enter Roll Number: 5
Enter Name: irshad
Enter Marks: 709
Do you want to add more records? (y/n): y
Enter Roll Number: 6
Enter Name: wahid
Enter Marks: 840
Do you want to add more records? (y/n): n
——————————–
Process exited after 40.15 seconds with return value 0
Press any key to continue . . .