C++ | Saving data into files(.dat)

Introduction

This is a tutorial for saving the data into .dat file in C++. The program is given below that save the worker’s data into Data.dat file and reads the data from the file. The program is extendable. Go enjoy the program. Lets begin………..

Program for saving data into files in C++.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
class worker
{
 public:
 char name[30];
 int sal;
 void getdata(void)
 {
 cout<<"Enter Worker's name:";
 cin>>name;
 cout<<"Enter salary:";
 cin>>sal;
 }

};
void main()
{
//clear the screen
clrscr();
//declare the object
worker w;
//getdata for worker w
w.getdata();
//declare ofstream object.
ofstream ofile;
//open the ofile
ofile.open("Data.dat");
//save the data
ofile.write((char*)&w,sizeof(w));
//close ofile
ofile.close();
//declare ifstream object.
ifstream ifile;
//open the ifile.
ifile.open("Data.dat");
//new worker obj.
worker ww;
//read the data from file.
ifile.read((char*)&ww,sizeof(ww));
//close ifile
ifile.close();
//print
cout<<"Name:"<<ww.name<<endl;
cout<<"Salary:"<<ww.sal;
//get character
getch();
}

Output

Enter Worker’s name:abc
Enter salary:1200
Name:abc
Salary:1200

Note:- The data is saved in Data.dat file that is mostly found in BIN folder.

How does it work.

  1. You enter name.
  2. You enter salary.
  3. The data is saved in Data.dat file.
  4. The data is taken from the file in new object and is printed.

Extending it.

The program is extendable. You can make the same program for students and you can even use structure for that. This is basic concept of c++ and can be used in any program.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ and ‘fstream.h’ files.
  2. Declare the class, their variables and functions.
  3. Add void main.
  4. Start program by first clearing the screen.
  5. Declare the worker class.
  6. Call the function to get data.
  7. Declare the ofstream object.
  8. Call the open.
  9. Call write function.
  10. Call close function.
  11. Declare the ifstream object.
  12. Call the open function.
  13. Call the read function.
  14. Call the close function.
  15. Add the cout to print the data.

At the end

You learnt creating the C++ program for saving data in .dat files. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: