Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, November 17, 2024

File Stream Operations: Opening and Closing a File

 Working with Files

  1. Include the <fstream> Library
    To use file handling features, include the <fstream> library:

#include <fstream>

Opening and Closing a File
Files are opened using the open() method or during object creation. Always close files after use with close().

Example:


#include <iostream>

#include <fstream>

using namespace std;

int main() {

    // Write to a file

    ofstream outfile("example.txt");

    if (outfile.is_open()) {

        outfile << "Hello, File Handling in C++!\n";

        outfile.close();

    } else {

        cout << "Unable to open file for writing.\n";

    }


    // Read from a file

    ifstream infile("example.txt");

    string line;

    if (infile.is_open()) {

        while (getline(infile, line)) {

            cout << line << endl; // Print the content to the console

        }

        infile.close();

    } else {

        cout << "Unable to open file for reading.\n";

    }

    return 0;

}




Checking if a File is Open:

The is_open() method checks whether the file was successfully opened.


1 comment:

  1. Loved the way you present all the topics , it makes everything , especially learning very interesting and fascinating sir , hats off to you!

    ReplyDelete