Advertisement
file-stream-object("filename", mode);
File Mode | Description |
---|---|
ios::out | Searches for the file and opens it in write mode. If the file is found, its content are overwritten. If file is not found, a new file is created. Allows you to write to the file. |
//Creating a file for performing for output/write operation.
#include<fstream>
using namespace std;
int main()
{
//Using the ofstream class to create a file and to open an output stream to the file, to write content to it
ofstream ofstream_ob("File1.txt", ios::out);
int i = 10;
//writing an int value to the file using ofstream object
ofstream_ob<< i << "\n";
char ch = 'a';
//writing an char value to the file
ofstream_ob<< ch << "\n";
float f = 9.99f;
//Writing a float value to the file
ofstream_ob<< f << "\n";
char arr[] = "Hello World";
//writing a char array to the file
ofstream_ob<<"Hello World!" << "\n";
string str = "Keep smiling!";
//writing a string to the file
ofstream_ob<<"Keep Smiling!"<< "\n";
//closing the output stream after completing the write operation on the file
ofstream_ob.close();
return 0;
}
10
a
9.99
Hello World!
Keep Smiling!
Advertisement
//Creating a file for performing for output/write operation.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//Using the ofstream class to create a file and to open an output stream to the file, to write content to it
ofstream ofstream_ob("File2.txt", ios::out);
int i;
cout<<"Enter an int : ";
cin>>i;
//writing an int value to the file
ofstream_ob<< i << "\n";
char ch;
cout<<"Enter a char value : ";
cin>>ch;
//writing an char value to the file
ofstream_ob<< ch << "\n";
float f;
cout<<"Enter a float value : ";
cin>>f;
//Writing a float value to the file
ofstream_ob<< f << "\n";
char newline_chr;
cin.get(newline_chr);
char arr[40];
cout<<"Enter the content of char array : ";
cin.getline(arr,40);
cout<<arr;
//writing a char array to the file
ofstream_ob<< arr << "\n";
string str;
cout<<"Enter the content of a string : ";
getline(cin, str);
//writing a string to the file
ofstream_ob<< str<< "\n";
//closing the output stream after completing the write operation on the file
ofstream_ob.close();
return 0;
}
Enter an int : 10
Enter a char value : a
Enter a float value : 9.99
Enter the content of char array : Hello World!
Enter the content of a string : Keep Smiling
10
a
9.99
Hello World!
Keep Smiling
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement