Read from File

Reading Data from a File in C++

BeginnerTopic: File Handling Programs
Back

C++ Read from File Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    // Open file for reading
    ifstream inFile("data.txt");
    
    if (inFile.is_open()) {
        string line;
        
        cout << "Reading file line by line:" << endl;
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        
        inFile.close();
    } else {
        cout << "Error: Unable to open file for reading." << endl;
    }
    
    // Alternative: Read word by word
    ifstream inFile2("data.txt");
    if (inFile2.is_open()) {
        string word;
        cout << "\nReading file word by word:" << endl;
        while (inFile2 >> word) {
            cout << word << " ";
        }
        cout << endl;
        inFile2.close();
    }
    
    return 0;
}
Output
Reading file line by line:
Hello, World!
This is a C++ file handling program.
Line 3: Learning file operations.
100 200 300

Reading file word by word:
Hello, World! This is a C++ file handling program. Line 3: Learning file operations. 100 200 300

Understanding Read from File

Reading from a file uses ifstream (input file stream). Use getline() to read line by line, or >> operator to read word by word. The >> operator stops at whitespace. Always check if file opened successfully. The file pointer automatically moves forward as you read.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents