C++ File Handling write() Function
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
1 2 3 4 |
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
1 2 3 4 |
ofstream outfile; outfile .write ((char*)&emp,sizeof(emp)); |
C++ File Handling write() Function Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#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: