← Back to C++ Course | Chapter 15: File I/O | Lesson 2 of 6

C++ ifstream & ofstream

ofstream writes to files and ifstream reads from them, like a pen and a reading glasses for a notebook. They work much like cout and cin.
Syntax
cpp
#include <fstream>

std::ofstream out("filename.txt");
out << value;
out.close();

std::ifstream in("filename.txt");
in >> variable;
in.close();

Writing with ofstream

std::ofstream is specialized for writing to files, and reuses the insertion operator (<<) you already know from std::cout -- once a file is open, file << "text" writes to it exactly the same way cout << "text" writes to the console.

Example: Writing with ofstream

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ofstream file("data.txt");
	file << "Hello file";
	file.close();
	// Print to the console with cout
	std::cout << "Written" << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Reading with ifstream

std::ifstream is specialized for reading from files, using the extraction operator (>>) just like std::cin. It reads whitespace-delimited tokens one at a time -- numbers, words -- converting them to the target variable's type automatically.

Example: Reading with ifstream

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ofstream out("data.txt");
	out << "42";
	out.close();
	std::ifstream in("data.txt");
	int value;
	in >> value;
	// Print to the console with cout
	std::cout << value << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Reading Line by Line

Because >> stops at whitespace, it can't read a line containing spaces in one call -- reading "Hello World" would stop at "Hello". std::getline(stream, str) reads an entire line, including internal spaces, up to the next newline, which is what you want for sentence- or record-based file formats.

Example: Reading Line by Line

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>
#include <string>

// Program execution starts in main()
int main() {
	std::ofstream out("data.txt");
	out << "Hello World";
	out.close();
	std::ifstream in("data.txt");
	std::string line;
	std::getline(in, line);
	// Print to the console with cout
	std::cout << line << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Appending with ofstream

Opening a file with plain ofstream truncates it, discarding any existing content before writing begins.

Passing the ios::app flag instead positions every write at the end of the existing file, letting you add new data (like log entries) without destroying what was already saved.

Example: Appending with ofstream

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ofstream file("data.txt", std::ios::app);
	file << "Appended text";
	file.close();
	// Print to the console with cout
	std::cout << "Appended without truncating" << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Safe File Writing Practices

Beyond just checking is_open(), inspect the stream's state after each read or write -- a failed write (for example, from a full disk) sets the fail bit even though the stream opened successfully, and code that doesn't check this can silently lose data.

Example: Safe File Writing Practices

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ofstream file("data.txt");
	file << "Some data";
	// Check whether file.fail()
	if (file.fail()) {
		// Print to the console with cout
		std::cout << "Write failed" << std::endl;
	} else {
		// Print to the console with cout
		std::cout << "Write succeeded" << std::endl;
	}
	file.close();
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking that ofstream or ifstream opened successfully before using it, so a missing file goes unnoticed.
  2. Opening an existing file with ofstream in the default mode, which erases its old content; use ios::app to append.
  3. Reading lines with while (!file.eof()), which often processes the last line twice; loop on getline instead.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.