C++ File Handling Tutorial

C++ file handling enables programs to store data persistently by reading from and writing to files. The `` library is used for file operations.

Opening a File

Files can be opened in different modes using the `fstream`, `ifstream`, or `ofstream` classes:


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

int main() {
    ofstream outFile("example.txt");
    if (outFile.is_open()) {
        cout << "File opened successfully for writing." << endl;
        outFile.close();
    } else {
        cout << "Failed to open file." << endl;
    }
    return 0;
}
                

Writing to a File

Use the `ofstream` object to write data:


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

int main() {
    ofstream outFile("example.txt");
    if (outFile.is_open()) {
        outFile << "Hello, File Handling in C++!" << endl;
        outFile.close();
    }
    return 0;
}
                

Reading from a File

Use the `ifstream` object to read data:


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

int main() {
    ifstream inFile("example.txt");
    string content;
    if (inFile.is_open()) {
        while (getline(inFile, content)) {
            cout << content << endl;
        }
        inFile.close();
    }
    return 0;
}
                

File Modes

Files can be opened in modes like `ios::app`, `ios::binary`, and `ios::trunc` for specific use cases.

Closing a File

Always close files using the `.close()` method to ensure data integrity.

Best Practices

  • Always check if the file is open before performing operations.
  • Use exception handling for robust file I/O.
0 Interaction
2.4K Views
Views
34 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home