Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Files and Streams

C++ Files and Streams

In previous chapters, we used cin and coutfrom the C++ standard library to read data from the keyboard and output content to the screen.

In addition to standard I/O, C++ also supports file operations: you can save data to a file and read existing data from a file.

C++ provides file input/output through the header, which mainly contains the following three file stream classes:

File stream class Description
ofstream ofstream: output file stream, used to write data to a file; can create a file.
ifstream ifstream: input file stream, used to read data from a file.
fstream fstream: bidirectional file stream, can read from and write to a file.

When using file streams, you need to include the header:

#include 

If the program also needs to use cin, cout and other standard I/O objects, you need to include:

#include 

For example, create an object for writing to a file:

std::ofstream outfile("example.txt");

The code above attempts to open the example.txt file. If the file does not exist, a new file is usually created; if the file already exists, the original content is cleared by default.

Opening a File

Before reading or writing a file, you must first open it.

C++ can open a file directly through the file stream object's constructor, or first create the object and then use the open() open() member function.

Method 1: open the file when creating the object

std::ofstream outfile("example.txt");

Method 2: use the open() method

std::ofstream outfile;

outfile.open("example.txt");

Both methods can be used to open a file; the first is more concise.

open() A common form of the open() function is as follows:

void open(

    const char* filename,

    std::ios::openmode mode

);

Where:

The above is a simplified function declaration; different file stream classes have different default open modes. Modern C++ also supports using std::string to specify the filename, and since C++17 also supports std::filesystem::path.

File Open Modes

C++ provides various file open modes that you can choose from as needed.

Mode flag Description
ios::in Open the file in read mode.
ios::out Open the file in write mode.
ios::app Append mode; each write is positioned at the end of the file.
ios::ate After opening, position the file at the end, but it can be repositioned later.
ios::trunc Clear existing content when opening the file.
ios::binary Open the file in binary mode, avoiding conversions such as newline characters in text mode.

Multiple modes can be combined using the bitwise OR operator | .

For example, open the file in write mode and clear the original content:

std::ofstream outfile;

outfile.open("file.dat", std::ios::out | std::ios::trunc);

If you want to keep the original content and append new content to the end, you can use:

std::ofstream outfile;

outfile.open("file.dat", std::ios::app);

If you need to both read and write the file, you can use fstream:

std::fstream file;

file.open("file.dat", std::ios::in | std::ios::out);

**Note:** The above read-write mode usually requires the file to already exist. If you need to create a new file, you can combine write modes as needed, but be aware that trunc may clear the original content.

By default, the three file stream classes usually use the following open modes:

File stream class Default mode
ifstream ios::in
ofstream ios::out
fstream ios::in \| ios::out

Check Whether the File Opened Successfully

A file open operation may not necessarily succeed. For example, a missing file, wrong path, or lack of access permission can all cause the open to fail.

You can use the is_open() is_open() method to check whether the file opened successfully.

Example

#include

<

iostream

#include

<

fstream

using

namespace

std

;

int

main

(

)

{

ifstream

infile

(

"

example.txt

"

)

;

if

(

!

infile

.

is_open

(

)

)

{

cout

<<

"

File failed to open!

"

<<

endl

;

return

1

;

}

cout

<<

"

File opened successfully!

"

<<

endl

;

infile

.

close

(

)

;

return

0

;

}

If the file does not exist in the current working directory example.txt , the program will output:

文件打开失败!

Besides is_open()is_open(), you can also use fail(), bad() and other member functions to check the stream's state.

Closing a File

After a file is used, you can close it via the close() close() method.

The basic call is as follows:

outfile.close();

When closing a file, the file stream attempts to complete the necessary buffer flush and releases the association with the file.

C++ file stream objects also have automatic resource management. When a local file stream object goes out of scope and is destroyed, the associated file is automatically closed.

For example:

{

    std::ofstream file("example.txt");

    file << "Hello C++";

} // file 离开作用域,自动关闭文件

Therefore, it is not necessary to call close()explicitly every time. However, if you need to close the file early, reopen another file, or check for errors on closing, you can actively call close().

Writing to a File

In C++, you can use the output file stream ofstream, through the stream insertion operator << to write data to a file.

The usage method is similar to outputting cout content to the screen.

Example

#include

<

iostream

#include

<

fstream

using

namespace

std

;

int

main

(

)

{

// Create and open file

ofstream

outfile

(

"

example.txt

"

)

;

if

(

!

outfile

)

{

cerr

<<

"

Unable to open file!

"

<<

endl

;

return

1

;

}

// Write content to file

outfile

<<

"

Hello C++

"

<< '\

n

';

outfile

<<

"

Welcome to learning C++ file operations

"

<< '\

n

';

outfile

<<

"

Number:

"

<<

100

<< '\

n

';

// Close file

outfile

.

close

(

)

;

if

(

!

outfile

)

{

cerr

<<

"

File write or close failed!

"

<<

endl

;

return

1

;

}

cout

<<

"

File written successfully!

"

<<

endl

;

return

0

;

}

After the program executes normally, the screen outputs:

文件写入成功!

Meanwhile, in the current working directory, a example.txt file is generated with the following content:

Hello C++

欢迎学习 C++ 文件操作

数字:100

**Note:** If example.txt already exists, by default ofstream opening the file will clear the original content.

Appending to a file

If you do not want to clear the original content, but instead want to add data at the end of the file, you can use ios::app mode.

Example

#include

<

iostream

#include

<

fstream

using

namespace

std

;

int

main

(

)

{

// Open file in append mode

ofstream

outfile

(

"

example.txt

"

,

ios

::

app

)

;

if

(

!

outfile

)

{

cerr

<<

"

Unable to open file!

"

<<

endl

;

return

1

;

}

outfile

<<

"

This is a line of appended content.

"

<< '\

n

';

outfile

.

close

(

)

;

if

(

!

outfile

)

{

cerr

<<

"

File write failed!

"

<<

endl

;

return

1

;

}

cout

<<

"

Content appended successfully!

"

<<

endl

;

return

0

;

}

Each time the program runs, it tries to append a line of content at the end of the file, without actively clearing the existing data.

Reading a file

In C++, you can use the input file stream ifstream to read file content.

Common reading methods include:

Reading data with >>

The following demonstrates how to read two integers from a file.

Example

#include

<

iostream

#include

<

fstream

using

namespace

std

;

int

main

(

)

{

// First create a test file

{

ofstream

outfile

(

"

numbers.txt

"

)

;

if

(

!

outfile

)

{

cerr

<<

"

Failed to create file!

"

<<

endl

;

return

1

;

}

outfile

<<

"

100 200

"

<< '\

n

';

outfile

.

close

(

)

;

if

(

!

outfile

)

{

cerr

<<

"

Failed to write test file!

"

<<

endl

;

return

1

;

}

}

ifstream

infile

(

"

numbers.txt

"

)

;

if

(

!

infile

)

{

cerr

<<

"

Failed to read file!

"

<<

endl

;

return

1

;

}

int

a

,

b

;

if

(

infile

a

b

)

{

cout

<<

"

a =

"

<<

a

<<

endl

;

cout

<<

"

b =

"

<<

b

<<

endl

;

}

else

{

cerr

<<

"

File data format error!

"

<<

endl

;

return

1

;

}

return

0

;

}

Execution result:

a = 100

b = 200

Stream extraction operator >> reads content according to the target data type and, by default, skips leading whitespace characters.

If reading a string, for example infile >> name, it usually stops at a space, tab, or newline, so it is not suitable for reading a complete text line containing spaces.

Reading line by line with getline()

If you need to read text containing spaces, you can use getline().

Example

#include

<

iostream

#include

<

fstream

#include

<

string

using

namespace

std

;

int

main

(

)

{

ifstream

infile

(

"

example.txt

"

)

;

if

(

!

infile

)

{

cerr

<<

"

Unable to open file!

"

<<

endl

;

return

1

;

}

string

line

;

// Read line by line until end of file or read failure

while

(

getline

(

infile

,

line

)

)

{

cout

<<

line

<<

endl

;

}

if

(

infile

.

bad

(

)

)

{

cerr

<<

"

An error occurred while reading the file!

"

<<

endl

;

return

1

;

}

infile

.

close

(

)

;

return

0

;

}

If the file contains the following content:

Hello C++

Welcome to C++ programming

This is a text file.

When the program runs normally, it outputs the corresponding text line by line.

getline() By default it reads up to the newline character and saves the read content into string object, but does not save the line-ending delimiter.

**Note:** When using cin >> to read a number, then using getline(cin, ...) to read a whole line, you may need to first handle the remaining newline in the input buffer. This is because formatted input usually does not extract the trailing newline.

Read & Write Example

Below is a complete example demonstrating how to write user-input information to a file, then reopen the file and read its content.

The program will ask the user to enter a name and age, and save the data to the afile.dat file, then read and display it on the screen.

Example

#include

<

iostream

#include

<

fstream

#include

<

string

using

namespace

std

;

int

main

(

)

{

string

name

;

int

age

;

// Get user input

cout

<<

"

Enter your name:

"

;

getline

(

cin

,

name

)

;

cout

<<

"

Enter your age:

"

;

if

(

!

(

cin

age

)

)

{

cerr

<<

"

Invalid age!

"

<<

endl

;

return

1

;

}

// Open file in write mode

ofstream

outfile

(

"

afile.dat

"

)

;

if

(

!

outfile

)

{

cerr

<<

"

Cannot open file for writing!

"

<<

endl

;

return

1

;

}

// Write data

outfile

<<

name

<< '\

n

';

outfile

<<

age

<< '\

n

';

// Close file and check status

outfile

.

close

(

)

;

if

(

!

outfile

)

{

cerr

<<

"

Failed to write file!

"

<<

endl

;

return

1

;

}

// Reopen file in read mode

ifstream

infile

(

"

afile.dat

"

)

;

if

(

!

infile

)

{

cerr

<<

"

Cannot open file for reading!

"

<<

endl

;

return

1

;

}

string

readName

;

int

readAge

;

// Read name

if

(

!

getline

(

infile

,

readName

)

)

{

cerr

<<

"

Failed to read name!

"

<<

endl

;

return

1

;

}

// Read age

if

(

!

(

infile

readAge

)

)

{

cerr

<<

"

Failed to read age!

"

<<

endl

;

return

1

;

}

// Output file content

cout

<<

"

Reading from the file

"

<<

endl

;

cout

<<

"

Name:

"

<<

readName

<<

endl

;

cout

<<

"

Age:

"

<<

readAge

<<

endl

;

infile

.

close

(

)

;

return

0

;

}

When the program is compiled and executed, assuming the input name is Zara and age is 9, the result is as follows:

Enter your name: Zara

Enter your age: 9

Reading from the file

Name: Zara

Age: 9

After the program executes successfully,afile.dat the content of the file is:

Zara

9

Program explanation:

This example uses the write-first, then-close, then-reopen-and-read approach, making it easy for beginners to understand the file input/output process.

If you need to read and write within the same file stream object, you can use fstream, but you need to properly manage the read and write positions as well as the stream state.

File position pointer

A file stream maintains state related to the read/write position, used to determine where to read data from or write data to next.

Commonly used file position manipulation functions include:

member function Purpose
seekg() sets the read position of the input stream.
seekp() sets the write position of the output stream.
tellg() gets the current position of the input stream.
tellp() gets the current position of the output stream.

Among them, the letter g comes from get, meaning read; the letter p comes from put, meaning write.

seekg() and seekp()

seekg() and seekp() can use an absolute position, or an offset relative to a certain reference position.

Common reference positions include:

Reference position Description
ios::beg Offset is calculated from the beginning of the file.
ios::cur Offset is calculated from the current position.
ios::end Offset is calculated from the end of the file.

The following code shows common positioning methods:

Example

// Assume fileObject is an opened file input stream

// Seek to the beginning of the file

fileObject

.

seekg

(

0

,

ios

::

beg

)

;

// Move n position units forward from the beginning of the file

fileObject

.

seekg

(

n

,

ios

::

beg

)

;

// Move n position units forward from the current position

fileObject

.

seekg

(

n

,

ios

::

cur

)

;

// Move n position units backward from the end of the file

fileObject

.

seekg

(

n

,

ios

::

end

)

;

// Seek to the end of the file

fileObject

.

seekg

(

0

,

ios

::

end

)

;

The above code is used to illustrate how to call the functions, where n is an appropriate offset.

**Note:** In binary files, common implementations allow positioning by byte offset; in text mode, newline conversions or encoding issues may exist, so you should not simply treat all file positions as arbitrarily computable byte indices.

File position operation example

Below, create a binary file and write the string ABCDEFGHIJ, then use seekg() to read a character from a specified position.

Example

#include

<

iostream

#include

<

fstream

using

namespace

std

;

int

main

(

)

{

// Create binary file

ofstream

outfile

(

"

position.dat

"

,

ios

::

binary

)

;

if

(

!

outfile

)

{

cerr

<<

"

Failed to create file!

"

<<

endl

;

return

1

;

}

outfile

<<

"

ABCDEFGHIJ

"

;

outfile

.

close

(

)

;

if

(

!

outfile

)

{

cerr

<<

"

Failed to write file!

"

<<

endl

;

return

1

;

}

// Read file in binary mode

ifstream

infile

(

"

position.dat

"

,

ios

::

binary

)

;

if

(

!

infile

)

{

cerr

<<

"

Failed to open file!

"

<<

endl

;

return

1

;

}

char

ch

;

// Seek to position with offset 4

infile

.

seekg

(

4

,

ios

::

beg

)

;

if

(

!

infile

.

get

(

ch

)

)

{

cerr

<<

"

Failed to read file!

"

<<

endl

;

return

1

;

}

cout

<<

"

Character read:

"

<<

ch

<<

endl

;

// Return to the beginning of the file

infile

.

seekg

(

0

,

ios

::

beg

)

;

if

(

!

infile

.

get

(

ch

)

)

{

cerr

<<

"

Failed to read file!

"

<<

endl

;

return

1

;

}

cout

<<

"

First character:

"

<<

ch

<<

endl

;

infile

.

close

(

)

;

return

0

;

}

Execution result:

读取的字符:E

第一个字符:A

Because the file position starts counting from 0, the position with offset 4 corresponds to the 5th character E.

When using seekg() , you also need to pay attention to the stream state. If a previous read has reached the end of the file, the stream may have set an error state, and if necessary you should clear it via clear() to clear the state before repositioning.

Getting the file size

For ordinary binary files, you can combine seekg() and tellg() to get the file length.

Example

#include

<

iostream

#include

<

fstream

using

namespace

std

;

int

main

(

)

{

ifstream

infile

(

"

position.dat

"

,

ios

::

binary

|

ios

::

ate

)

;

if

(

!

infile

)

{

cerr

<<

"

Unable to open file!

"

<<

endl

;

return

1

;

}

// After opening the file, the read position is at the end of the file

streampos

size

=

infile

.

tellg

(

)

;

if

(

size

==

streampos

(

1

)

)

{

cerr

<<

"

Failed to get file size!

"

<<

endl

;

return

1

;

}

cout

<<

"

File size:

"

<<

size

<<

"

bytes

"

<<

endl

;

infile

.

close

(

)

;

return

0

;

}

If both the position.dat is the file generated in the previous example, containing 10 ASCII characters, typically outputting:

文件大小:10 字节

On common platforms and ordinary files, the end position of a binary stream can be used to obtain the byte length of the file. For modern C++ projects, you can also use the std::filesystem::file_size() provided by C++17 to get the size of ordinary files.

Notes on file operations

In practical development, file operations also need attention to the following issues:

For ordinary text files, it is recommended to use std::string and std::getline() to read content, avoiding issues such as input length limitations caused by fixed-length character arrays.

For binary files that require random access, you can combine read(), write(), seekg() and seekp() to achieve more flexible file operations.