0
0
C++programming~5 mins

File input using ifstream in C++

Choose your learning style9 modes available
Introduction

We use ifstream to read data from files. It helps us get information stored in files into our program.

When you want to read a list of names saved in a text file.
When you need to load settings or configuration from a file.
When you want to process data saved in a file, like numbers or text.
When you want to read a story or text from a file to display it.
When you want to read user data saved from a previous program run.
Syntax
C++
#include <fstream>

std::ifstream inputFile("filename.txt");

if (inputFile.is_open()) {
    // read from inputFile
    inputFile.close();
}

Always include <fstream> to use ifstream.

Check if the file opened successfully with is_open() before reading.

Examples
This reads a file line by line and prints each line.
C++
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream file("data.txt");
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::cout << line << '\n';
        }
        file.close();
    }
    return 0;
}
This reads integers from a file until no more numbers are left.
C++
#include <fstream>
#include <iostream>

int main() {
    std::ifstream file;
    file.open("numbers.txt");
    int number;
    if (file.is_open()) {
        while (file >> number) {
            std::cout << number << ' ';
        }
        file.close();
    }
    return 0;
}
Sample Program

This program opens a file named example.txt, reads each word one by one, and prints each word on its own line.

C++
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream inputFile("example.txt");
    if (!inputFile.is_open()) {
        std::cout << "Failed to open file.\n";
        return 1;
    }

    std::string word;
    while (inputFile >> word) {
        std::cout << word << '\n';
    }

    inputFile.close();
    return 0;
}
OutputSuccess
Important Notes

Remember to close the file after reading to free resources.

If the file does not exist or cannot be opened, is_open() returns false.

You can read words, lines, or other data types depending on how you use the input stream.

Summary

ifstream is used to read data from files.

Always check if the file opened successfully before reading.

Close the file when done to keep your program clean.