C++ File I/O

How to process a file in C++?

* A file is a collection of data or information that is stored on a computer or digital storage device. Files can contain a wide range of data types, including text, images, videos, audio, programs, and more.

File Processing

In C++, file I/O (Input/Output) operations are performed using streams. Streams are sequences of bytes that represent a flow of data. There are two main types of streams used for file I/O in C++: 'ifstream' (input file stream) and 'ofstream' (output file stream). Additionally, there is a combined stream called 'fstream' that can be used for both input and output operations.

C++ provides several classes and functions in the '<fstream>' library for file handling.

File Modes:

File modes are used to specify the intended operations on a file when opening it. The modes are specified as flags when creating an instance of a file stream class, such as 'std::ifstream' for reading from a file or 'std::ofstream' for writing to a file. The following are some commonly used file modes:

1. std::ios::in Open for input operations. It is used for reading from the file.

std::ifstream inputFile("filename.txt", std::ios::in);

2. std::ios::out Open for output operations. It is used for writing to the file. If the file already exists, its content is truncated.

std::ofstream outputFile("filename.txt", std::ios::out);

3. std::ios::app Append mode. All output operations are performed at the end of the file, appending to its existing content.

std::ofstream outputFile("filename.txt", std::ios::app);

And,

4. std::ios::ate allows to open the file and move the file pointer to the end immediately. This is useful if you want to both read and write to the file and want to start writing at the end.

5. std::ios::binary helps to open the file in binary mode, which means that the file is treated as a binary rather than a text file. This is important for files that may contain non-textual data.

6. std::ios::trunc: find if the file already exists, truncate its content to zero length.

File Reading

To read from a file, you can use the '>>' operator, 'getline()', or other stream extraction methods. Here's a simple example that demonstrates how to open a file and read its contents:

example.txt
txt (Text File) Copy Code
The file opened & read successfully.
main.cpp
cpp Copy Code
#include<iostream>
#include<fstream>
#include<string>

int main() {
    // Open a file for reading
    std::ifstream inputFile("example.txt");

    // Read and display the contents of the file line by line
    std::string line;
    while (std::getline(inputFile, line)) {
        std::cout << line << std::endl;
    }

    // Close the file
    inputFile.close();

    return 0;
}

We use a 'while' loop along with 'std::getline' to read each line from the file and then print it to the console.

• close() It's a member function of file stream classes that closes the associated file. It's important to close files explicitly when you are done reading or writing to them to release system resources and ensure that all data is properly flushed to the file.

Output:
The file opened & read successfully.

Why do I ignore the 'std::ios::in' in this example?

The program we provided doesn't explicitly specify a file mode when opening the file. By default, when we create an instance of 'std::ifstream' (input file stream), it is opened in the 'std::ios::in' mode, which is the default mode for reading.

In the line:

std::ifstream inputFile("input.txt");

The file "input.txt" is opened in the default input mode ('std::ios::in'). This mode allows you to read from the file. If the file does not exist, the stream will still be created, but reading from it will not be possible.

Note: In this case, it explicitly specifies the input mode, but as mentioned earlier, it's not strictly necessary since 'std::ios::in' is the default mode for 'std::ifstream'.

File Writing

To write to a file, you use the '<<' operator or other stream insertion methods. Here's an example writing strings to a file:

cpp Copy Code
#include<iostream>
#include<fstream>

int main() {
    // Open a file for writing
    std::ofstream outFile("example.txt");

    // Write data to the file
    outFile << "Hello, this is a sample text." << std::endl;
    outFile << "Writing to a file in C++ is easy!" << std::endl;

    // Close the file
    outFile.close();

    std::cout << "Data has been written to the file." << std::endl;

    return 0;
}

We open a file named "example.txt" using 'std::ofstream' in output mode ('ofstream' is a subclass of 'ostream').

Output:
The file opened & read successfully.

Remember: To handle errors appropriately, such as checking if the file is opened successfully before attempting to write data. Additionally, you should check for errors after writing to the file to ensure that the write operation was successful.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.