User Program Communication

Write to File in C++

Used to write to a file.


Syntax
#include <iostream>
#include <fstream>
using namespace std;

ofstream newFile;
newFile.open(fileName);
if (openFile.is_open()){ //checking for existence of file
    openFile << valueToWrite;
    openFile.close(); //closes file after done
}

Notes

Ofstream is an object created which represents the file being written to.


Example
#include <iostream>
#include <fstream>
using namespace std;

int main(){
    ofstream helloWorld;
    helloWorld.open("helloworld.txt");
    if (helloWorld.is_open()){ //checking for existence of file
        helloWorld << "Hello, World!";
        helloWorld.close(); //closes file after done
    }
}

< Read from Text File   |   Local Variables >

© 2019 SyntaxDB. All Rights Reserved.