C++ Writing to file
In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file.
Syntax
file-stream-class file-stream-object; file-stream-object.write((char *)&var , sizeof (var));
The write() takes two arguments. The first argument is the address of variable var and the second argument is the size of variable var in bytes.
Example
ofstream outfile; outfile .write ((char*)&emp,sizeof(emp));
C++ File Handling write() Function Example
#include <iostream> #include <fstream> using namespace std; class employee { private: char name[30]; float salary; public: void getData(void) { cout<<"Enter name:"; cin.getline(name,sizeof(name)); cout<<"Enter salary:"; cin>>salary; } }; int main() { employee emp; ofstream file; file.open("employee.txt",ios::out);//open file in write mode if(!file) { cout<<"File not found"<<endl; return 0; } cout<<"File created successfully."<<endl; emp.getData(); file.write((char*)&emp,sizeof(emp)); //write into file file.close(); //close the file cout<<"File save and closed succesfully."<<endl; return 0; }
Output: