C++ Academy · Lesson

Reading Files with ifstream

Read text and data.

Lesson 1 of 413 steps

Reading Files with ifstream is a free C++ Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

What Is ifstream?

std::ifstream (input file stream) reads data from files. It behaves like std::cin but its source is a file on disk.

  • Defined in <fstream>.
  • Opens a file by name in its constructor.
#include <iostream>
#include <fstream>

int main() {
    std::ofstream("demo.txt") << "hello\n";
    std::ifstream in("demo.txt");
    std::string word;
    in >> word;
    std::cout << word << '\n';
    return 0;
}

Opening a File

Construct an ifstream with a filename, then check with is_open() whether the file was found.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("data.txt") << "42\n";
    std::ifstream in("data.txt");
    std::cout << (in.is_open() ? "opened" : "failed") << '\n';
    return 0;
}

Reading Words

The >> operator reads whitespace-separated tokens, just like with cin.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("words.txt") << "alpha beta gamma\n";
    std::ifstream in("words.txt");
    std::string w;
    while (in >> w) std::cout << w << '\n';
    return 0;
}

Reading Numbers

You can extract numeric types directly. Stream extraction parses the text into the right type.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("nums.txt") << "10 20 30\n";
    std::ifstream in("nums.txt");
    int sum = 0, x;
    while (in >> x) sum += x;
    std::cout << "sum = " << sum << '\n';
    return 0;
}

Reading Lines with getline

Use std::getline() to read a whole line including spaces, up to the newline.

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ofstream("lines.txt") << "first line\nsecond line\n";
    std::ifstream in("lines.txt");
    std::string line;
    while (std::getline(in, line)) std::cout << "[" << line << "]\n";
    return 0;
}

Reading the Whole File

To slurp an entire file, read it into a string using stream buffer iterators.

#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    std::ofstream("all.txt") << "line1\nline2\n";
    std::ifstream in("all.txt");
    std::stringstream ss;
    ss << in.rdbuf();
    std::cout << ss.str();
    return 0;
}

Detecting End of File

A read loop ends when extraction fails, typically at end of file. Testing the stream in a condition checks for this.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("eof.txt") << "1 2 3\n";
    std::ifstream in("eof.txt");
    int x, count = 0;
    while (in >> x) ++count;
    std::cout << "read " << count << " numbers\n";
    std::cout << "eof: " << std::boolalpha << in.eof() << '\n';
    return 0;
}

Handling a Missing File

If the file does not exist, the stream is in a failed state and is_open() is false. Always check before reading.

#include <iostream>
#include <fstream>

int main() {
    std::ifstream in("does_not_exist_12345.txt");
    if (!in) {
        std::cout << "could not open file\n";
    }
    return 0;
}

Parsing Structured Lines

Combine getline with istringstream to parse fields out of each line.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main() {
    std::ofstream("people.txt") << "Alice 30\nBob 25\n";
    std::ifstream in("people.txt");
    std::string line;
    while (std::getline(in, line)) {
        std::istringstream ss(line);
        std::string name; int age;
        ss >> name >> age;
        std::cout << name << " is " << age << '\n';
    }
    return 0;
}

Explicit open and close

You can open a default-constructed stream later with open() and release it with close().

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("oc.txt") << "data\n";
    std::ifstream in;
    in.open("oc.txt");
    std::string s; in >> s;
    in.close();
    std::cout << s << '\n';
    return 0;
}

RAII Closes for You

When an ifstream goes out of scope, its destructor closes the file automatically. Manual close() is rarely needed.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("raii.txt") << "x\n";
    {
        std::ifstream in("raii.txt");
        std::string s; in >> s;
        std::cout << s << '\n';
    } // file closed here automatically
    std::cout << "closed\n";
    return 0;
}

Quick Check

Test your understanding of reading lines.

Recap

You learned that std::ifstream:

  • reads from files using >> and std::getline
  • should be checked with is_open() or by testing the stream
  • closes automatically via RAII when it goes out of scope

Next, you'll write files with ofstream.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Reading Files with ifstream” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Reading Files with ifstream”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Reading Files with ifstream”?

Read text and data. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Reading Files with ifstream” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Files with ifstream
  2. Writing Files with ofstream
  3. Binary File I/O
  4. Error Handling and State
← Back to C++ Academy