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

C++ File Handling Introduction

File handling is how your program reads and writes files, like opening a notebook to read or write. You open the file, do your job, and close it.
Syntax
cpp
#include <fstream>

std::ofstream file_name("filename.txt");  // open for writing
std::ifstream file_name("filename.txt");  // open for reading
file_name.close();

Streams and Files

C++ handles file I/O through the fstream library, which builds on the same stream abstraction as cin and cout.

Instead of reading from the keyboard or writing to the console, file streams read from and write to a file on disk, using nearly identical syntax to what you already know from console I/O.

Example: Streams and Files

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 using the same << stream style as cout" << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Opening a File

You can open a file either by calling the open() member function on an existing stream object, or by passing the file path straight into the stream's constructor -- the constructor form opens the file immediately, saving a separate call.

Example: Opening a File

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

// Program execution starts in main()
int main() {
	std::ofstream file1;
	file1.open("data.txt");
	std::ofstream file2("data.txt");
	file1 << "Line 1";
	file1.close();
	file2.close();
	// Print to the console with cout
	std::cout << "Opened both ways" << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Checking if File Open Succeeded

A file might fail to open for many reasons -- a typo in the path, missing permissions, or a nonexistent directory -- so always call is_open() (or check the stream in a boolean context) before attempting to read or write.

Skipping this check leads to silent failures where every subsequent operation just does nothing.

Example: Checking if File Open Succeeded

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");
	// Check whether file.is_open()
	if (file.is_open()) {
		file << "Success";
		file.close();
	}
	// Print to the console with cout
	std::cout << "Checked before writing" << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Closing a File

C++ automatically closes an open file stream when its destructor runs, typically at the end of scope, which prevents most resource leaks even if you forget.

Still, calling close() explicitly once you're done is good practice -- it flushes buffered writes to disk immediately rather than waiting for scope exit.

Example: Closing a File

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 << "Content";
	file.close();
	// Print to the console with cout
	std::cout << "Closed explicitly" << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

File Open Modes

Open mode flags like ios::out (write, overwriting existing content) and ios::app (append to the end without erasing what's already there) control what happens to existing file content.

Choosing the wrong mode is a common bug -- accidentally using ios::out when you meant to append will silently wipe a file's contents.

Example: File Open Modes

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 line\n";
	file.close();
	// Print to the console with cout
	std::cout << "Appended using ios::app" << std::endl;
	// 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 whether the file opened successfully before reading or writing.
  2. Forgetting to close the file, so buffered data may not be written.
  3. Using the wrong relative path so the file is not found.
🔒

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.