read and write file in c++

include

include

using namespace std;

int main() { // Writing to a file ofstream outfile; outfile.open("example.txt"); // Creating a file named example.txt

if (outfile.is_open()) { // Check if the file is open
    outfile << "This is a sample text written to the file." << endl; // Writing to the file
    outfile.close(); // Closing the file
} else {
    cout << "Unable to open file for writing." << endl; // Display an error if unable to open the file
}

// Reading from a file
ifstream infile;
infile.open("example.txt"); // Opening the file for reading

if (infile.is_open()) { // Check if the file is open
    string line;
    while (getline(infile, line)) { // Read and display each line
        cout << line << endl;
    }
    infile.close(); // Close the file
} else {
    cout << "Unable to open file for reading." << endl; // Display an error if unable to open the file
}

return 0;

}