ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP1112File Io Operations
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP1112

    Programming Fundamentals

    Progress0 / 19 done
    Topics19
    1Introduction to Problem Solving2Von-Neumann Architecture3Introduction to Programming4Role of Compiler and Linker5Introduction to Algorithms6Basic Data Types and Variables7Input/Output Constructs8Arithmetic, Comparison and Logical Operators9Conditional Statements and Execution Flow10Repetitive Statements and Execution Flow11Lists and Memory Organization12Multi-dimensional Lists13Introduction to Modular Programming14Function Definition and Calling15Stack Rolling and Unrolling16Strings and String Operations17Pointers/References18Static and Dynamic Memory Allocation19File I/O Operations
    4 min read
    Topic 19 of 19
    Topic Study Note Illustration
    19

    File I/O Operations

    File Input/Output (I/O) operations in C++ allow programs to read from and write to files, enabling data persistence beyond the execution of a program. C++ provides robust...

    File I/O Operations in C++

    File Input/Output (I/O) operations in C++ allow programs to read from and write to files, enabling data persistence beyond the execution of a program. C++ provides robust libraries for file handling through the Standard Library, primarily using fstream, ifstream, and ofstream classes.

    1. File Streams

    C++ uses streams to represent data being read from or written to files. The main file stream classes are:

    • ifstream: Used for reading from files.
    • ofstream: Used for writing to files.
    • fstream: Used for both reading and writing.

    2. Including the Required Header

    To perform file I/O operations, include the <fstream> header:

    #include <fstream>
    #include <iostream>
    #include <string>
    

    3. Opening a File

    Before you can read from or write to a file, you must open it. You can specify the mode in which to open the file:

    • ios::in: Open for reading.
    • ios::out: Open for writing (overwrites the file).
    • ios::app: Open for appending (adds to the end of the file).
    • ios::binary: Open in binary mode.

    Example of Opening a File:

    std::ifstream inputFile("example.txt"); // Open for reading
    std::ofstream outputFile("output.txt"); // Open for writing
    

    4. Writing to a File

    To write data to a file, you can use the ofstream class. Here’s how to do it:

    Example:

    std::ofstream outFile("output.txt");
    
    if (outFile.is_open()) {
        outFile << "Hello, World!" << std::endl;
        outFile << "Writing to a file in C++." << std::endl;
        outFile.close(); // Always close the file after writing
    } else {
        std::cerr << "Unable to open file for writing." << std::endl;
    }
    

    5. Reading from a File

    To read data from a file, use the ifstream class. You can read line by line or word by word.

    Example:

    std::ifstream inFile("example.txt");
    
    if (inFile.is_open()) {
        std::string line;
        while (std::getline(inFile, line)) { // Read line by line
            std::cout << line << std::endl;
        }
        inFile.close(); // Always close the file after reading
    } else {
        std::cerr << "Unable to open file for reading." << std::endl;
    }
    

    6. Checking File Status

    You can check if a file is open and handle errors appropriately using the is_open() method. You can also check if reading or writing was successful.

    Example:

    if (!inFile) {
        std::cerr << "Error opening file." << std::endl;
    }
    

    7. Working with Binary Files

    For binary files, use the ios::binary flag when opening the file. You can read and write data in binary format.

    Example:

    std::ofstream binaryFile("data.bin", std::ios::binary);
    
    int num = 42;
    binaryFile.write(reinterpret_cast<char*>(&num), sizeof(num)); // Write integer to binary file
    binaryFile.close();
    
    std::ifstream readBinary("data.bin", std::ios::binary);
    int readNum;
    readBinary.read(reinterpret_cast<char*>(&readNum), sizeof(readNum)); // Read integer from binary file
    readBinary.close();
    

    8. Error Handling

    It’s essential to handle errors when performing file I/O operations. You can use the fail() method to check if the last operation was successful.

    Example:

    if (outFile.fail()) {
        std::cerr << "Error writing to file." << std::endl;
    }
    

    Summary

    File I/O operations in C++ provide a way to read from and write to files, enabling data persistence. The use of ifstream, ofstream, and fstream classes allows for flexible and efficient handling of text and binary files. Proper error handling and closing files are crucial for ensuring that file operations are performed correctly. Understanding these concepts is vital for developing applications that require data storage and retrieval.

    ← Previous topic 18
    Static and Dynamic Memory Allocation

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    4mremaining
    598words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals