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 : Micheal 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 contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- How to make a C++ class whose objects can only be dynamically allocated?
- How to convert a class to another class type in C++?
- C++ Classes and Objects
- Passing and Returning Objects in C++
- When are static objects destroyed?
- How to restrict dynamic allocation of objects in C++?
- Comparing String objects using Relational Operators in C++
- Count the number of objects using Static member function
- CSV file management using C++
- tellp() in file handling with c++ with example
- clocale header file in C++
- File Handling through C++ Classes
- Four File Handling Hacks which every C/C++ Programmer should know
- Find sum of integers in a file which contains any characters
- C Program to find size of a File