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 contribute.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.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- How to make a C++ class whose objects can only be dynamically allocated?
- How to restrict dynamic allocation of objects in C++?
- When are static objects destroyed?
- C++ Classes and Objects
- Comparing String objects using Relational Operators in C++
- Count the number of objects using Static member function
- How to initialize Array of objects with parameterized constructors in C++
- Introduction to Complex Objects and Composition
- Life cycle of Objects in C++ with Example
- Passing and Returning Objects in C++
- How to convert a class to another class type in C++?
- Difference between Base class and Derived class in C++
- Implement your own tail (Read last n lines of a huge file)
- Four File Handling Hacks which every C/C++ Programmer should know
- lseek() in C/C++ to read the alternate nth byte and write it in another file
- Print "Hello World" in C/C++ without using any header file
- C++ program to print unique words in a file
- Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
- Find sum of integers in a file which contains any characters
- tellp() in file handling with c++ with example
Improved By : zytekaron