Read/Write Class Objects from/to File in C++
Given a file “Input.txt” in which every line has values same as instance variables of a class.
Read the values into the class’s object and do necessary operations.
The data transfer is usually done using '>>' and <<' operators. But if you have a class with 4 data members and want to write all 4 data members from its object directly to a file or vice-versa, we can do that using following syntax : To write object's data members in a file : // Here file_obj is an object of ofstream file_obj.write((char *) & class_obj, sizeof(class_obj)); To read file's data members into an object : // Here file_obj is an object of ifstream file_obj.read((char *) & class_obj, sizeof(class_obj));
Input : Input.txt : Michael 19 1806 Kemp 24 2114 Terry 21 2400 Operation : Print the name of the highest rated programmer. Output : Terry
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.