C++ Reading file
In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file.
Syntax
file-stream-class file-stream-object; file-stream-object.read((char *)&var , sizeof (var));
<h3">Example
ofstream outfile; outfile . read((char*)&emp,sizeof(emp));
C++ File Handling read() Function Example
Reading the content of existing file 'employee.txt'.
#include <iostream> #include <fstream> using namespace std; class employee { private: char name[30]; float salary; public: void showData(void) { cout<<"Name:"<<name<<endl; cout<<"Salary:"<<salary<<endl; } }; int main() { employee emp; //open file in input mode and read data ifstream file; file.open("employee.txt",ios::in); if(!file){ cout<<"Error in opening file."; return 0; } //read data from file file.read((char*)&emp,sizeof(emp)); emp.showData(); file.close(); return 0; }
Output:
