Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Files C++ Exceptions C++ Date

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Certificate


C++ ofstream Class

❮ fstream classes


Example

Use ofstream to write to a file:

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

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file
  MyFile << "Files can be tricky, but it is fun enough!";

  // Close the file
  MyFile.close();
} 

Definition and Usage

The ofstream class (short for "output file stream") is used to write into files.

The ofstream class is defined in the <fstream> header file.

To open a file, pass the file path into the constructor:

ofstream MyFile("filename.txt");

The << insertion operator and a variety of functions can be used to write into the file.


The Insertion Operator

The << insertion operator writes a literal value or the contents of a variable into the file.

int year = 2024;
MyFile << year << "\n";
MyFile << "Files can be tricky, but it is fun enough!";

Manipulators

Manipulators change the formatting of the data that is written to the file. They are used with the << insertion operator in the same way as literal values and variables.

Except for setw(), the effect of a manipulator remains until another another manipulator changes it.

Some useful manipulators are shown in the table below.

Manipulator Description Example
boolalpha Writes boolean values as "true" and "false" instead of "1" and "0". MyFile << boolalpha << false;
dec Represents integers as decimal digits. MyFile << dec << 12;
endl Writes a newline character. This manipulator also flushes the output buffer which makes it less efficient than printing \n. MyFile << "Line 1" << endl << "Line 2";
ends Writes the \0 null terminating character used to end C-style strings. MyFile << "Hello World!" << ends;
fixed Represents floating point numbers with a fixed number of decimal places. The number of decimal places can be established with the setprecision() manipulator. MyFile << fixed << 19.99;
hex Represents integers as hexadecimal digits. MyFile << hex << 12;
internal If a width is specified (using the setw() manipulator), numbers will have their sign left-aligned while the value is right-aligned, other data types will have the output aligned to the right. MyFile << setw(10) << internal << -12345;
left If a width is specified (using the setw() manipulator), aligns output to the left. MyFile << setw(10) << left << "Hello";
noboolalpha Used to reset the change made by the boolalpha manipulator. MyFile << noboolalpha << false;
noshowbase Used to reset the change made by the showbase manipulator. MyFile << hex << noshowbase << 12;
noshowpoint Used to reset the change made by the showpoint manipulator. MyFile << noshowpoint << 12345.0;
noshowpos Used to reset the change made by the showpos manipulator. MyFile << noshowpos << 12;
nouppercase Used to reset the change made by the uppercase manipulator. MyFile << hex << nouppercase << 12;
oct Represents integers as octal digits. MyFile << oct << 12;
right If a width is specified (using the setw() manipulator), aligns output to the right. MyFile << setw(10) << right << "Hello";
scientific Represents floating point numbers in scientific notation. The number of decimal places can be established with the setprecision() manipulator. MyFile << fixed << 19.99;
setfill() Chooses a character to use as padding.
Requires the <iomanip> library.
MyFile << setfill('.') << setw(10) << 19.99;
setprecision() Chooses the precision of floating point numbers. If the fixed or scientific manipulators were used it specifies the number of decimal places, otherwise it specifies the number of significant digits.
Requires the <iomanip> library.
MyFile << setprecision(4) << 12.3456;
setw() Specifies the minimum number of characters wide the next output should be. If the output is not wide enough then padding is added to fill up the remaining space.
Requires the <iomanip> library.
MyFile << setw(10) << "Hello";
showbase When representing integers as hexadecimal or octal, prefixes the numbers with "0x" or "0" to show their base. MyFile << hex << showbase << 12;
showpoint Always writes the decimal point for floating point numbers even if it is not needed. MyFile << showpoint << 12345.0;
showpos Always writes a + sign next to positive numbers. MyFile << showpos << 12;
uppercase Represents hexadecimal digits and the scientific notation "e" in uppercase. MyFile << hex << uppercase << 12;

File Writing Functions

The file writing functions write data into a file and move the file pointer to the first position after the written content.

write()

The write(str, n) method writes n characters from the char array str into the file.

char myStr[] = "Hello World!";
MyFile.write(myStr, 5);

put()

The put(c) method writes the specified character c into the file.

char grade = 'B';
MyFile.put(grade);

File Handling Functions

File handling functions open, close and navigate files.

open()

The open(filepath) method opens the file at the path specified by filepath. If a file is already open then this method has no effect.

ofstream MyFile;
MyFile.open("filename.txt");

is_open()

The is_open() method returns true if a file is open and false if there is no file open.

ofstream MyFile;
cout << MyFile.is_open(); << "\n"; // Displays 0 because the file is not open
MyFile.open("filename.txt");
cout << MyFile.is_open(); << "\n"; // Displays 1 because the file is open

close()

The close() method closes a file. It is good to close a file when you are finished working with it to free up resources.

MyFile.close();

rdbuf()

The rdbuf() method returns a pointer to the internal filebuf object which directly handles the file.

filebuf * buf = MyFile.rdbuf();

seekp()

The seekp(position) method moves the file pointer to a specified position relative to the beginning of the file.

MyFile.seekp(6)

The seekp(position, origin) method moves the file pointer to a specified position in the file relative to an origin. The origin has three possible values:

  • ofstream::beg - The position is relative to the beginning of the file.
  • ofstream::cur - The position is relative to the current file position.
  • ofstream::end - The position is relative to the end of the file.

Move the file pointer to different positions:

MyFile.seekp(6, ofstream::beg);
cout << MyFile.tellp(); << "\n";
MyFile.seekp(-3, ofstream::cur);
cout << MyFile.tellp(); << "\n";
MyFile.seekp(-4, ofstream::end);
cout << MyFile.tellp(); << "\n";

tellp()

The tellp() method returns the current position of the file pointer in the file.

cout << MyFile.tellp();

❮ fstream classes

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.