File Handling

File handling in C++ involves various operations such as defining and opening a file, closing a file, reading from a file, and writing into a file.

Defining, Opening and Closing a File

To define and open a file in C++, you typically use the fstream library, which provides classes for handling file input and output operations. The ofstream class is used for writing to files, and the ifstream class is used for reading from files. You can also use the fstream class, which supports both reading and writing.

#include <fstream>
using namespace std;
 
int main() {
    // Define and open a file for writing
    ofstream outputFile("eniv.txt");
 
    // Write data to the file
    outputFile << "Hello, Eniv" << endl;
 
    // Close the file
    outputFile.close();
 
    return 0;
}

Explanation:

  • This code defines and opens a file named "eniv.txt" for writing.
  • It writes the string Hello, Eniv into the file.
  • Finally, it closes the file.

No direct output is printed to the console. However, if you open the "eniv.txt" file, you will find the text "Hello, Eniv" written into it.

Reading from a File

To read data from a file in C++, you can use the ifstream class along with input stream extraction operators (>> or getline() function) to read data from the file.

#include <fstream>
#include <iostream>
using namespace std;
 
int main() {
    // Define and open a file for reading
    ifstream inputFile("eniv.txt");
 
    // Read data from the file
    string line;
    while (getline(inputFile, line)) {
        cout << line << endl;
    }
 
    // Close the file
    inputFile.close();
 
    return 0;
}

Explanation:

  • This code defines and opens a file named "eniv.txt" for reading.
  • It then reads each line from the file and prints it to the console using cout.
  • The content of "eniv.txt" will be printed to the console line by line.

This code reads the contents of a file named "eniv.txt" in the current directory, printing each line to the console. Make sure the file "eniv.txt" exists in the directory before running the program.

Writing into a File

To write data into a file in C++, you can use the ofstream class along with output stream insertion operators << to write data into the file.

#include <fstream>
using namespace std;
 
int main() {
    // Define and open a file for writing
    ofstream outputFile("eniv.txt");
 
    // Write data to the file
    outputFile << "Hello, Eniv" << endl;
 
    // Close the file
    outputFile.close();
 
    return 0;
}

Explanation:

  • This code defines and opens a file named "eniv.txt" for writing.
  • It writes the string "Hello, Eniv" into the file.
  • No direct output is printed to the console. The file "eniv.txt" will contain the text "Hello, Eniv" after execution.

In real-world applications, it's important to include error handling mechanisms when working with files to handle potential issues such as file not found, permission denied, or file corruption. This ensures robustness and reliability of the program.

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
 
int main() {
    ifstream inputFile("eniv.txt");
 
    // Check if file opened successfully
    if (!inputFile.is_open()) {
        cerr << "Error: Unable to open file." << endl;
        return 1;
    }
 
    // Read data from the file
    string line;
    while (getline(inputFile, line)) {
        cout << line << endl;
    }
 
    // Close the file
    inputFile.close();
 
    return 0;
}

In this code:

  • We attempt to open the file "eniv.txt" for reading.
  • If the file cannot be opened successfully, an error message is printed to the standard error stream (cerr) using cerr. Then the program exits with a non-zero status code.
  • If the file is opened successfully, its contents are read and printed to the console as before.
  • Finally, the file is closed.

Templates

In C++, templates provide a way to write generic code that can work with any data type. Without templates, developers would need to duplicate code for each data type they want to work with, leading to code redundancy and maintenance overhead. Templates enable the creation of functions and classes that can operate on multiple data types without sacrificing type safety or efficiency.

Function Templates

Function templates in C++ allow you to define functions that can work with any data type. You specify a generic data type parameter in the function definition, and the compiler generates versions of the function for each data type it's used with. This enables code reuse and simplifies the implementation of generic algorithms.

Here's an example of a function template that finds the maximum of two values:

#include <iostream>
using namespace std;
 
// Function template to find the maximum of two values
template <typename T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}
 
int main() {
    // Usage of function template with integers
    cout << "Max of 5 and 7: " << maximum<int>(5, 7) << endl;
 
    // Usage of function template with floating-point numbers
    cout << "Max of 3.14 and 2.71: " << maximum<float>(3.14, 2.71) << endl;
 
    // Usage of function template with characters
    cout << "Max of 'A' and 'B': " << maximum<char>('A', 'B') << endl;
 
    return 0;
}

Output:

Max of 5 and 7: 7
Max of 3.14 and 2.71: 3.14
Max of 'A' and 'B': B

Explanation:

  • We define a function template maximum that takes two parameters of type T and returns the maximum of the two values.
  • We use the typename keyword to declare T as a placeholder for the data type.
  • Inside the main function, we use the maximum function template with different data types (integers, floating-point numbers, and characters).
  • The compiler generates versions of the maximum function for each data type used, ensuring type safety and efficient code execution.
How's article quality?

Last updated on -

Page Contents