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
    🧩
    Object Oriented Programming
    CSI-312
    Progress0 / 16 topics
    Topics
    1. Evolution of Object-Oriented (OO) Programming2. Object-Oriented (OO) Concepts and Principles3. Problem Solving in OO Paradigm4. OO Programme Design Process5. Classes6. Methods7. Objects and Encapsulation8. Constructors and Destructors9. Operator Overloading10. Function Overloading11. Virtual Functions12. Derived Classes13. Inheritance14. Polymorphism15. I/O and File Processing16. Exception Handling
    CSI-312›I/O and File Processing
    Object Oriented ProgrammingTopic 15 of 16

    I/O and File Processing

    8 minread
    1,308words
    Intermediatelevel

    I/O and File Processing in C++

    Input/Output (I/O) operations and file processing are essential aspects of C++ programming. They allow interaction with external devices (like keyboards, screens) and the ability to read from or write to files, which are key for persistent data storage.

    C++ provides several libraries for handling I/O operations and file processing:

    • Standard I/O (Console I/O): Using streams like cin, cout, cerr, and clog.
    • File I/O: Using file stream classes like fstream, ifstream, and ofstream.

    1. Console Input/Output (Standard I/O)

    Standard I/O is used to interact with the console (screen for output and keyboard for input). C++ provides several predefined streams for console I/O.

    Output (Writing to Console)

    The output in C++ is typically done using the cout object, which is part of the <iostream> header. The << operator is used to send data to the console.

    #include <iostream>
    using namespace std;
    
    int main() {
        int number = 5;
        cout << "Hello, World!" << endl;
        cout << "The number is: " << number << endl;
    
        return 0;
    }
    

    Explanation:

    • cout: The standard output stream.
    • <<: The stream insertion operator that inserts data into the output stream.

    Output:

    Hello, World!
    The number is: 5
    

    Input (Reading from Console)

    For input, C++ uses the cin object, which reads input from the keyboard. The >> operator is used to extract data from the input stream.

    #include <iostream>
    using namespace std;
    
    int main() {
        int number;
        cout << "Enter a number: ";
        cin >> number;
        cout << "You entered: " << number << endl;
    
        return 0;
    }
    

    Explanation:

    • cin: The standard input stream.
    • >>: The stream extraction operator that extracts data from the input stream.

    Output (user input is assumed):

    Enter a number: 10
    You entered: 10
    

    2. File I/O in C++

    File I/O in C++ is accomplished using the file stream classes, which allow for reading from and writing to files. The classes are:

    • ifstream: Input file stream used to read from files.
    • ofstream: Output file stream used to write to files.
    • fstream: A combination of both ifstream and ofstream, used for both reading and writing.

    These classes are defined in the <fstream> header.

    Opening a File

    Before performing I/O operations, a file must be opened using the open() method or by directly passing the file name to the constructor of ifstream, ofstream, or fstream.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        // Create an object of ofstream (output file stream)
        ofstream outFile("example.txt");
    
        // Check if the file was successfully opened
        if (!outFile) {
            cout << "File could not be opened!" << endl;
            return 1; // Exit if file opening fails
        }
    
        // Write to the file
        outFile << "This is a line written to the file." << endl;
    
        // Close the file
        outFile.close();
    
        return 0;
    }
    

    Explanation:

    • The ofstream object outFile opens the file example.txt for writing.
    • If the file is successfully opened, the program writes a line to the file.
    • Always close the file after performing I/O operations using close().

    Output (in example.txt):

    This is a line written to the file.
    

    Reading from a File

    Reading from a file is done using the ifstream class, which reads from an existing file.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        // Create an object of ifstream (input file stream)
        ifstream inFile("example.txt");
    
        // Check if the file was successfully opened
        if (!inFile) {
            cout << "File could not be opened!" << endl;
            return 1; // Exit if file opening fails
        }
    
        string line;
        // Read and display each line from the file
        while (getline(inFile, line)) {
            cout << line << endl;
        }
    
        // Close the file
        inFile.close();
    
        return 0;
    }
    

    Explanation:

    • The ifstream object inFile opens the file example.txt for reading.
    • getline() reads a line of text from the file and stores it in the string variable line.
    • The file is closed after the reading operation.

    Output:

    This is a line written to the file.
    

    File I/O with fstream (Reading and Writing)

    If you need both reading and writing capabilities for the same file, you can use the fstream class.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        // Create an object of fstream (input-output file stream)
        fstream file("example.txt", ios::in | ios::out);
    
        // Check if the file was successfully opened
        if (!file) {
            cout << "File could not be opened!" << endl;
            return 1; // Exit if file opening fails
        }
    
        string line;
        // Read and display the current content of the file
        while (getline(file, line)) {
            cout << "Reading from file: " << line << endl;
        }
    
        // Write a new line to the file
        file.clear();  // Clear any EOF flag
        file.seekp(0, ios::end);  // Move the write pointer to the end
        file << "This is a new line added to the file." << endl;
    
        // Close the file
        file.close();
    
        return 0;
    }
    

    Explanation:

    • The fstream object file is opened with both input and output flags (ios::in | ios::out).
    • After reading, the file pointer is moved to the end using seekp() to append new content.
    • The clear() function is used to clear any EOF flag set by reading.

    File Modes in C++

    File operations in C++ are controlled by file modes, which determine the way files are opened. The file mode is specified when opening a file and can be set using the ios flags.

    Common file modes include:

    1. ios::in: Open for reading.
    2. ios::out: Open for writing.
    3. ios::app: Open for appending (writing at the end of the file).
    4. ios::ate: Open for reading and writing. The file pointer is at the end when opened.
    5. ios::trunc: Truncate the file to zero length when opened (the file is emptied).
    6. ios::binary: Open in binary mode (default is text mode).

    Example of using different file modes:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        // Open file in append mode
        ofstream outFile("example.txt", ios::app);
        if (!outFile) {
            cout << "Failed to open file!" << endl;
            return 1;
        }
    
        outFile << "Adding this line at the end." << endl;
        outFile.close();
    
        return 0;
    }
    

    Error Handling in File I/O

    C++ provides methods to check for file errors, ensuring robust file handling:

    • is_open(): Checks if the file was successfully opened.
    • eof(): Checks if the end-of-file has been reached.
    • fail(): Checks if an error occurred during the last file operation.
    • clear(): Clears error flags like eof() or fail().

    Example of checking if a file opens successfully:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        ifstream inFile("nonexistent.txt");
    
        if (!inFile) {
            cout << "Error: Unable to open file." << endl;
            return 1;
        }
    
        // Read from the file if it opened successfully
        inFile.close();
        return 0;
    }
    

    Conclusion

    • Console I/O: C++ uses cin and cout for reading and writing data to and from the console.
    • File I/O: C++ provides ifstream, ofstream, and fstream to handle file reading, writing, and both operations.
    • File Modes: You can specify how to open a file (read, write, append, etc.) using different file modes.
    • Error Handling: It’s important to check whether the file operations are successful to avoid runtime errors.

    By understanding and using I/O and file processing efficiently, you can interact with users and work with persistent data in C++ applications.

    Previous topic 14
    Polymorphism
    Next topic 16
    Exception Handling

    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 time8 min
      Word count1,308
      Code examples0
      DifficultyIntermediate