Super friendly <br/>code & developer communities

Super friendly
code & developer communities

A place for coders and developers to share, learn and grow together.

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

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++.

class worker
 char name[30];
 int sal;
 void getdata(void)
 cout<<"Enter Worker's name:";
 cout<<"Enter salary:";

void main()
//clear the screen
//declare the object
worker w;
//getdata for worker w
//declare ofstream object.
ofstream ofile;
//open the ofile"Data.dat");
//save the data
//close ofile
//declare ifstream object.
ifstream ifile;
//open the ifile."Data.dat");
//new worker obj.
worker ww;
//read the data from file.*)&ww,sizeof(ww));
//close ifile
//get character


Enter Worker’s name:abc
Enter salary:1200

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.

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.

P.S. If you have any questions, click here to join our community and feel free to ask any questions.