ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    COMP1112
    Progress0 / 19 topics
    Topics
    1. Introduction to Problem Solving2. Von-Neumann Architecture3. Introduction to Programming4. Role of Compiler and Linker5. Introduction to Algorithms6. Basic Data Types and Variables7. Input/Output Constructs8. Arithmetic, Comparison and Logical Operators9. Conditional Statements and Execution Flow10. Repetitive Statements and Execution Flow11. Lists and Memory Organization12. Multi-dimensional Lists13. Introduction to Modular Programming14. Function Definition and Calling15. Stack Rolling and Unrolling16. Strings and String Operations17. Pointers/References18. Static and Dynamic Memory Allocation19. File I/O Operations
    COMP1112›File I/O Operations
    Programming FundamentalsTopic 19 of 19

    File I/O Operations

    4 minread
    598words
    Beginnerlevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count598
      Code examples0
      DifficultyBeginner