Reading a File in C++ using fstream 📄

 


In C++, we use ifstream (input file stream) from the <fstream> library to read data from a file.


1️⃣ Steps to Read from a File

  1. Include <fstream> for file handling.
  2. Create an ifstream object to open the file.
  3. Use the >> operator (for word-by-word reading) or getline() (for line-by-line reading).
  4. Close the file using .close().

2️⃣ Basic Example: Reading from a File

#include <iostream>
#include <fstream>  // File handling
using namespace std;

int main() {
    ifstream file("example.txt");  // Open file

    if (file.is_open()) {
        string data;
        while (getline(file, data)) {  // Read line by line
            cout << data << endl;
        }
        file.close();  // Close file
    } else {
        cout << "Error opening file!" << endl;
    }

    return 0;
}

🔹 Sample example.txt Content

Hello, this is a file write example in C++!
Writing to files is simple!

🔹 Output

Hello, this is a file write example in C++!
Writing to files is simple!

✅ The program reads and displays the content line by line.


3️⃣ Reading Word by Word

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("example.txt");

    if (file.is_open()) {
        string word;
        while (file >> word) {  // Read word by word
            cout << word << endl;
        }
        file.close();
    } else {
        cout << "Error opening file!" << endl;
    }

    return 0;
}

🔹 Output

Hello,
this
is
a
file
write
example
in
C++!
Writing
to
files
is
simple!

✅ This reads each word separately.


4️⃣ Reading File Character by Character

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("example.txt");

    if (file.is_open()) {
        char ch;
        while (file.get(ch)) {  // Read character by character
            cout << ch;
        }
        file.close();
    } else {
        cout << "Error opening file!" << endl;
    }

    return 0;
}

🔹 Output

Hello, this is a file write example in C++!
Writing to files is simple!

✅ Reads character-by-character, preserving spaces.


5️⃣ Checking if File Exists Before Reading

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("non_existing_file.txt");

    if (!file) {  // Check if file exists
        cout << "File not found!" << endl;
    } else {
        string data;
        while (getline(file, data)) {
            cout << data << endl;
        }
        file.close();
    }

    return 0;
}

🔹 Output

File not found!

✅ Prevents errors if the file does not exist.


6️⃣ Reading and Storing in a Variable

#include <iostream>
#include <fstream>
#include <sstream>  // For stringstream
using namespace std;

int main() {
    ifstream file("example.txt");

    if (file.is_open()) {
        stringstream buffer;
        buffer << file.rdbuf();  // Read entire file into buffer
        file.close();
        
        string fileContent = buffer.str();  // Store in a string
        cout << "File Content:\n" << fileContent << endl;
    } else {
        cout << "Error opening file!" << endl;
    }

    return 0;
}

🔹 Output

File Content:
Hello, this is a file write example in C++!
Writing to files is simple!

✅ Stores entire file content in a string variable.


7️⃣ Summary

ifstream file("filename.txt"); → Open file for reading.
Use getline(file, data) → Read line by line.
Use file >> word → Read word by word.
Use file.get(ch) → Read character by character.
Use buffer << file.rdbuf(); → Read entire file at once.
Check if (!file) to prevent errors if the file does not exist.

Would you like a file handling project example next? 🚀

Post a Comment

0 Comments