File Operations in CPP



 File I/O (Input/Output) in C++ enables a program to read and write data to and from files. Configuration management, data logging, permanent storage, and other uses for this are beneficial. To manage file operations, C++ includes a set of classes in the header.

Key Classes in <fstream>
ifstream (Input File Stream): Used for reading data from files.
ofstream (Output File Stream): Used for writing data to files.
fstream (File Stream): Can be used for both reading and writing.

Basic Steps for File I/O:
  • Include the necessary header:
    • #include <fstream>
  • Create an object of ifstream, ofstream, or fstream.
  • Open the file using the .open() method or via the constructor.
  • Check if the file opened successfully by using .is_open().
  • Perform file operations (read/write).
  • Close the file using  .close().
Writing to a File (ofstream):
Using an ofstream object, you can write data to a file. If the file already exists, it will be overwritten; otherwise, it will be created.

Example:

#include <iostream>
#include <fstream>  // Include fstream for file operations

using namespace std;

int main() {
    ofstream outFile("example.txt");  // Create and open a file for writing

    if (outFile.is_open()) {
        outFile << "Hello, World!" << endl;  // Write to the file
        outFile << "Writing some text to a file." << endl;
        outFile.close();  // Close the file after writing
        cout << "File written successfully!" << endl;
    } else {
        cout << "Unable to open the file for writing!" << endl;
    }

    return 0;
}


Reading from a File (ifstream):

You can use an ifstream object to read data from a file. To prevent the software from not being able to open the file, make sure it is there.

Example:
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream inFile("example.txt");  // Open a file for reading
    string line;

    if (inFile.is_open()) {
        while (getline(inFile, line)) {  // Read the file line by line
            cout << line << endl;        // Print each line
        }
        inFile.close();  // Close the file after reading
    } else {
        cout << "Unable to open the file for reading!" << endl;
    }

    return 0;
}


Using fstream for Both Reading and Writing:

The fstream class can be used for both reading and writing. It is useful when you need to open a file in read-write mode.

Example:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    fstream file("example.txt", ios::in | ios::out);  // Open file for both reading and writing

    if (file.is_open()) {
        // Write to the file
        file << "This is a read-write file example." << endl;

        // Move the file pointer to the beginning
        file.seekg(0);  // Seek to the beginning for reading

        // Read from the file
        string line;
        while (getline(file, line)) {
            cout << line << endl;
        }

        file.close();  // Close the file after reading and writing
    } else {
        cout << "Unable to open the file!" << endl;
    }

    return 0;
}



File Open Modes:

When opening a file, you can specify the mode in which you want to open it. These modes are combined using the | operator.

Some commonly used file open modes:

ios::in: Open for reading.
ios::out: Open for writing (overwrites the file).
ios::app: Open for writing in append mode (adds to the end of the file without overwriting).
ios::binary: Open in binary mode (for non-text files like images).
ios::trunc: If the file already exists, truncate its content (default for ios::out).
ios::ate: Open and move the file pointer to the end of the file.

Example: Append Mode

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream outFile("example.txt", ios::app);  // Open file in append mode

    if (outFile.is_open()) {
        outFile << "Appending a new line to the file." << endl;
        outFile.close();  // Close the file after appending
        cout << "Data appended successfully!" << endl;
    } else {
        cout << "Unable to open the file for appending!" << endl;
    }

    return 0;
}


Reading and Writing Binary Files:

Although binary files (such as pictures or compiled data) may need to be read or written, text files are relatively straightforward. Use the ios::binary flag for binary files.

Writing Binary Data:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream outFile("data.bin", ios::binary);  // Open a binary file for writing

    if (outFile.is_open()) {
        int num = 12345;
        outFile.write(reinterpret_cast<char*>(&num), sizeof(num));  // Write the integer in binary form
        outFile.close();
    } else {
        cout << "Unable to open the file!" << endl;
    }

    return 0;
}


Reading Binary Data:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream inFile("data.bin", ios::binary);  // Open a binary file for reading

    if (inFile.is_open()) {
        int num;
        inFile.read(reinterpret_cast<char*>(&num), sizeof(num));  // Read the binary data
        cout << "The number is: " << num << endl;
        inFile.close();
    } else {
        cout << "Unable to open the file!" << endl;
    }

    return 0;
}



Checking File States:

C++ offers multiple ways to verify a file's status following an operation:

  • .eof() determines whether the end of the file (EOF) has been reached.
  • .good() verifies whether there were no mistakes
  • .fail(): Determines whether a non-fatal I/O error (such as a type mismatch) happened
  • .bad(): Determines whether a fatal I/O error happened.

Example:

#include <iostream>
#include <fstream>

using namespace std;

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

    if (inFile.is_open()) {
        string line;
        while (getline(inFile, line)) {
            cout << line << endl;
        }

        if (inFile.eof()) {
            cout << "End of file reached." << endl;
        } else if (inFile.fail()) {
            cout << "File read failed." << endl;
        } else if (inFile.bad()) {
            cout << "Fatal error occurred while reading." << endl;
        }

        inFile.close();
    } else {
        cout << "Unable to open the file!" << endl;
    }

    return 0;
}


 Closing Files:
When you're through with a file, it's crucial to close it to free up system resources and prevent corruption or data loss. Apply the.close() function:

outFile.close();






Post a Comment

0 Comments