0% found this document useful (0 votes)
12 views20 pages

C++ Fstream Class

The C++ fstream class is utilized for reading and writing files, defined in the <fstream> header. It provides various functions for file manipulation, including seekg(), tellg(), seekp(), tellp(), and methods for reading and writing data. Additionally, it includes file handling functions like open(), close(), and is_open() to manage file operations effectively.

Uploaded by

xilvenkat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views20 pages

C++ Fstream Class

The C++ fstream class is utilized for reading and writing files, defined in the <fstream> header. It provides various functions for file manipulation, including seekg(), tellg(), seekp(), tellp(), and methods for reading and writing data. Additionally, it includes file handling functions like open(), close(), and is_open() to manage file operations effectively.

Uploaded by

xilvenkat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

C++ fstream Class


❮ fstream classes

Example
Use fstream to read and write to a file:

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

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

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Read from the file


string myText;
getline(MyFile, myText);
cout << myText;

// Close the file

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 1/20
11/3/25, 6:07 PM C++ fstream fstream class

MyFile.close();
 } Tutorials  References  Exercises  Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

Definition and Usage


The fstream class (short for "file stream") is used to read and write into files.

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

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

fstream MyFile("filename.txt");

The fstream class has a variety of functions for reading and writing files which are listed
below.

File Pointer Functions


File pointers are internal variables which indicate where in the file to read or write.

File pointer functions are used to manipulate file pointers. There are functions for both a read
file pointer and a write file pointer, but the fstream class uses the same pointer for both
actions, so changing one of them also changes the other one.

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

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 2/20
11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In


MyFile.seekg(6)
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

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

fstream::beg - The position is relative to the beginning of the file.


fstream::cur - The position is relative to the current file position.
fstream::end - The position is relative to the end of the file.

Move the read file pointer to different positions:

MyFile.seekg(6, fstream::beg);
cout << MyFile.tellg() << "\n";
MyFile.seekg(-3, fstream::cur);
cout << MyFile.tellg() << "\n";
MyFile.seekg(-4, fstream::end);
cout << MyFile.tellg() << "\n";

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

cout << MyFile.tellg();

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

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 3/20
11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In


MyFile.seekp(6)
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

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

fstream::beg - The position is relative to the beginning of the file.


fstream::cur - The position is relative to the current file position.
fstream::end - The position is relative to the end of the file.

Move the write file pointer to different positions:

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

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

cout << MyFile.tellp();

File Reading Functions


File reading functions extract characters from a file and move the file pointer.

get()
https://www.w3schools.com/cpp/ref_fstream_fstream.asp 4/20
11/3/25, 6:07 PM C++ fstream fstream class

The get() method reads a single character from a file and returns its ASCII value as an int
 Tutorials  References  Exercises 
value. Convert it to a char type to see the character. The file pointer is moved to the next
Sign In

character in the file.


HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

char myChar = MyFile.get();


cout << myChar;

The get(destination, size, delimiter) method writes up to size characters to the


destination with data read from the file. It stops reading as soon as it reaches a line break, end
of file, or an optional character given by the delimiter parameter. The value written in
destination always ends with a \0 null terminating character. This method moves the file
pointer to the line break or delimiter where it stopped reading.

char destination[20];
MyFile.get(destination, 20);
cout << destination << "\n";

// Stop reading when a '.' is found


MyFile.get(destination, 20, '.');
cout << destination << "\n";

getline()
The getline(destination, size, delimiter) method is the same as the
get(destination, size, delimiter) method, except that the line break or delimiter is
discarded and the file pointer is moved to the character that follows it.

char destination[20];
MyFile.getline(destination, 20);
cout << destination << "\n";

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 5/20
11/3/25, 6:07 PM C++ fstream fstream class

// Stop reading when a '.' is found


 Tutorials  References  20,
MyFile.getline(destination, Exercises
'.');
Sign In

cout << destination << "\n";


HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

There is a similar getline(stream, destination, delimiter) function which reads all of


the characters up to the next line break (or optional delimiter) from the file specified by the
fstream object in the stream parameter and writes them into the string specified by
destination.

string destination;
getline(MyFile, destination);
cout << destination << "\n";

// Stop reading when a '.' is found


getline(MyFile, destination, '.');
cout << destination << "\n";

read()
The read(destination, n) method reads n characters from the file and writes them into the
char array specified by the destination parameter. Unlike other functions, it does not stop
reading at line breaks and it does not add a null terminating character to the data.

char destination[20];
MyFile.read(destination, 19);
destination[20] = '\0'; // Make sure it ends with a null terminating charac
cout << destination << "\n";

 

peek()

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 6/20
11/3/25, 6:07 PM C++ fstream fstream class

The peek() method reads a single character from a file and returns its ASCII value as an int
 Tutorials  References  Exercises  Sign In
value. Convert it to a char type to see the character. Unlike the get() method, this method
does not move the file pointer.
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

char myChar = MyFile.peek();


cout << myChar;

gcount()
The gcount() method returns the number of characters extracted from the file by most
recently called file reading method.

char destination[20];
MyFile.getline(destination, 20);
cout << MyFile.gcount() << "\n";

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 and
moves the file pointer forward by n characters.

char myStr[] = "Hello World!";


MyFile.write(myStr, 5);

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 7/20
11/3/25, 6:07 PM C++ fstream fstream class

put() Tutorials 
 References  Exercises  Sign In

The put(c)
HTML CSS method writes the specified
JAVASCRIPT SQL character c into
PYTHON JAVAthe file
PHPand moves
HOW the
TO file W3.CSS
pointer C
forward by one character.

char grade = 'B';


MyFile.put(grade);

File Handling Functions


File handling functions open and close 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.

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

 

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 8/20
11/3/25, 6:07 PM C++ fstream fstream class

close()Tutorials 
 References  Exercises  Sign In

The close()
HTML CSS method closes a file.
JAVASCRIPT SQLIt is good to closeJAVA
PYTHON a file when
PHPyou are
HOWfinished
TO working
W3.CSSwith C
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();

The Extraction Operator


The >> extraction operator reads a number of characters from the current position in the file,
interprets them and writes the interpreted value into a variable. Then the file pointer is moved
to the next character which has not yet been read. The way that the characters are interpreted
depends on the data type of the variable.

Syntax

MyFile >> variable

It can also be used multiple times to read parts of a file one after another.

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 9/20
11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In


MyFile >> variable1 >> variable2 >> variable3
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

The >> extraction operator starts by skipping over whitespace characters (spaces, tabs and line
breaks) until it reaches the first character that is not whitespace. After that, it follows the rules
shown in the following table based on the data type of the variable.

Data Description Examples


Type

int Reads a sequence of digits and interprets them as an integer. The 15


long sequence may be preceded by a sign ("+" or "-"). It stops reading at +125
short the first character that is not a digit. -30
If a valid sequence is not found the ifstream object will fail and
stop reading further.

bool Reads an integer in the same way as described above and then 0
interprets 0 as false and 1 as true. Any other integer value will be 1
interpreted as true but the ifstream object will fail and stop +01
reading further.
The boolalpha manipulator described in the next section
completely changes this behavior.

float Reads a valid sequence of characters and interprets them as a 5


double floating point number. A valid sequence has at least one digit, it can -5.46
be preceded by a sign ("+" or "-") and it can be followed by a +2e4
decimal point and decimal digits. Scientific notation (a number -1.62E-5
followed by "e" or "E" and some digits) can also be used.
If a valid sequence is not found the fstream object will fail and
stop reading further.

char Reads a single character from the file. B


If the file pointer is at the end of the file the fstream object will fail
and stop reading further.

string Reads all of the characters up to the next whitespace (space, tab or Hello
char * line break), null terminating character or end of file. The variable will
have a \0 null terminating character added to the value.

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 10/20
11/3/25, 6:07 PM C++ fstream fstream class

If the file pointer is already at a null terminating character or at the


 Tutorials  References  Exercises 
end of the file the fstream object will fail and stop reading further.
Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
Manipulators
A manipulator can be used in place of a variable. When manipulators are used they change how
data is interpreted by the fstream object. The effect of a manipulator remains until another
manipulator changes it.

The following table has a list of manipulators that can be used with the >> extraction operator.

Manipulator Description

noskipws Instead of skipping over whitespace characters the >> extraction operator
will read them. This is mainly useful for char type variables because with
other data types it stops reading when it runs into whitespace.

skipws Resets the change made by the noskipws manipulator.

ws Moves the file pointer to the next position of the file that does not have
whitespace.

hex Expect hexadecimal representations (digits 0 to 9 and A to F) of numbers


when using integer variables.

oct Expect octal representations (digits 0 to 7) of numbers when using integer


variables.

dec Expect decimal representations (digits 0 to 9) of numbers when using


integer variables. This resets the change made by the hex and oct
manipulators.

boolalpha When reading data for a boolean variable, instead of looking for an integer
it looks for the character sequence "true" or "false".

noboolalpha Resets the change made by the boolalpha manipulator.

Example

Use manipulators to change how data is interpreted:

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 11/20
11/3/25, 6:07 PM C++ fstream fstream class

bool Tutorials
myBool; References  Exercises  Sign In
int myInt;
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
// Interpret character sequences "true" and "false" as boolean values
MyFile >> boolalpha >> myBool;

// Revert to reading booleans normally


MyFile >> noboolalpha;

// Read hexadecimal numbers from the file and interpret them as integers
MyFile >> hex >> myInt;

// Revert to reading integers normally


MyFile >> dec;

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.

The table below shows a list of useful manipulators:

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 12/20
11/3/25, 6:07 PM C++ fstream fstream class

Manipulator
Tutorials  References 
Description
Exercises 
Example
Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
boolalpha Writes boolean values as "true" and "false" MyFile <<
instead of "1" and "0". boolalpha <<
false;

dec Represents integers as decimal digits. MyFile << dec <<


12;

endl Writes a newline character. This MyFile << "Line


manipulator also flushes the output buffer 1" << endl <<
which makes it less efficient than printing "Line 2";
\n .

ends Writes the \0 null terminating character MyFile << "Hello


used to end C-style strings. World!" << ends;

fixed Represents floating point numbers with a MyFile << fixed


fixed number of decimal places. The << 19.99;
number of decimal places can be
established with the setprecision()
manipulator.

hex Represents integers as hexadecimal digits. MyFile << hex <<


12;

internal If a width is specified (using the setw() MyFile <<


manipulator), numbers will have their sign setw(10) <<
left-aligned while the value is right-aligned, internal <<
other data types will have the output -12345;
aligned to the right.

left If a width is specified (using the setw() MyFile <<


manipulator), aligns output to the left. setw(10) << left
<< "Hello";

noboolalpha Used to reset the change made by the MyFile <<


boolalpha manipulator. noboolalpha <<

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 13/20
11/3/25, 6:07 PM C++ fstream fstream class

false;
 Tutorials  References  Exercises  Sign In

noshowbase Used to reset the change made by the MyFile


HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO<< hex <<
W3.CSS C
showbase manipulator. noshowbase << 12;

noshowpoint Used to reset the change made by the MyFile <<


showpoint manipulator. noshowpoint <<
12345.0;

noshowpos Used to reset the change made by the MyFile <<


showpos manipulator. noshowpos << 12;

nouppercase Used to reset the change made by the MyFile << hex <<
uppercase manipulator. nouppercase <<
12;

oct Represents integers as octal digits. MyFile << oct <<


12;

right If a width is specified (using the setw() MyFile <<


manipulator), aligns output to the right. setw(10) << right
<< "Hello";

scientific Represents floating point numbers in MyFile << fixed


scientific notation. The number of decimal << 19.99;
places can be established with the
setprecision() manipulator.

setfill() Chooses a character to use as padding. MyFile <<


Requires the <iomanip> library. setfill('.') <<
setw(10) <<
19.99;

setprecision() Chooses the precision of floating point MyFile <<


numbers. If the fixed or scientific setprecision(4)
manipulators were used it specifies the << 12.3456;
number of decimal places, otherwise it

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 14/20
11/3/25, 6:07 PM C++ fstream fstream class

specifies the number of significant digits.


 Tutorials  References  Exercises 
Requires the <iomanip> library.
Sign In

HTML CSS
 setw() JAVASCRIPT SQLminimum
Specifies the PYTHON
number JAVA
of PHP HOW TO W3.CSS C
MyFile <<
characters wide the next output should be. setw(10) <<
If the output is not wide enough then "Hello";
padding is added to fill up the remaining
space.
Requires the <iomanip> library.

showbase When representing integers as hexadecimal MyFile << hex <<


or octal, prefixes the numbers with "0x" or showbase << 12;
"0" to show their base.

showpoint Always writes the decimal point for floating MyFile <<
point numbers even if it is not needed. showpoint <<
12345.0;

showpos Always writes a + sign next to positive MyFile << showpos


numbers. << 12;

uppercase Represents hexadecimal digits and the MyFile << hex <<
scientific notation "e" in uppercase. uppercase << 12;

❮ fstream classes

ADVERTISEMENT

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 15/20
11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 16/20
11/3/25, 6:07 PM C++ fstream fstream class

COLOR PICKER
 Tutorials  References  Exercises  Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

 
Recommended videos Powered by Snigel

ADVERTISEMENT

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 17/20
11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

REMOVE ADS

ADVERTISEMENT ADVERTISEMENT

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 18/20
11/3/25, 6:07 PM C++ fstream fstream class

 Tutorials  References  Exercises  Sign In

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C

 PLUS SPACES

GET CERTIFIED FOR TEACHERS

FOR BUSINESS CONTACT US

Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial

Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 19/20
11/3/25, 6:07 PM C++ fstream fstream class
Python Reference

 Tutorials  W3.CSS Reference


References 
Bootstrap Reference
Exercises  Sign In
PHP Reference
HTML
 CSS HTML ColorsSQL
JAVASCRIPT PYTHON JAVA PHP HOW TO W3.CSS C
Java Reference
AngularJS Reference
jQuery Reference

Top Examples Get Certified


HTML Examples HTML Certificate
CSS Examples CSS Certificate
JavaScript Examples JavaScript Certificate
How To Examples Front End Certificate
SQL Examples SQL Certificate
Python Examples Python Certificate
W3.CSS Examples PHP Certificate
Bootstrap Examples jQuery Certificate
PHP Examples Java Certificate
Java Examples C++ Certificate
XML Examples C# Certificate
jQuery Examples XML Certificate

    

FORUM ABOUT ACADEMY


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-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

https://www.w3schools.com/cpp/ref_fstream_fstream.asp 20/20

You might also like