C++ fstream write to text file

Introduction

To write to a file, we use file stream << operator:

#include <fstream> 

int main() //from w w  w. j a v a2s .c  o  m
{ 
    std::fstream fs{ "myoutputfile.txt", std::ios::out }; 
    fs << "First line of text." << '\n'; 
    fs << "Second line of text" << '\n'; 
    fs << "Third line of text" << '\n'; 
} 

We associate an fs object with an output file name and provide an additional std::ios::out flag which opens a file for writing and overwrites any existing myoutputfile.txt file.

Then we output our text to a file stream using the << operator.

We can also output strings to our file using the file stream's << operator:

#include <iostream> 
#include <fstream> 
#include <string> 

int main() /*from www  . j  a  v  a 2  s  . c om*/
{ 
    std::fstream fs{ "myoutputfile.txt", std::ios::out }; 
    std::string s1 = "The first string.\n"; 
    std::string s2 = "The second string.\n"; 
    fs << s1 << s2; 
} 



PreviousNext

Related