top of page
Writer's picturecompnomics

Text and Binary Streams in C++ file handling


C++ provides a powerful and flexible I/O system based on stream classes. These classes allow you to perform various operations on input and output streams, including text and binary data.


Text Streams

Text streams are used to read and write text data, character by character. They are typically used for human-readable data, such as text files, console input/output, etc.


Key Points about Text Streams:

  • Character-Oriented: Text streams operate on characters, which are typically represented by ASCII or Unicode codes.

  • Formatted I/O: You can use formatted I/O operators like << and >> to read and write formatted data.

  • Newline Character: The newline character (\n) is used to separate lines of text.


Example:

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

using namespace std;

int main() {
    // Writing to a text file
    ofstream outfile("text.txt");
    outfile << "Hello, world!" << endl;
    outfile.close();

    // Reading from a text file
    ifstream infile("text.txt");
    string line;
    while (getline(infile, line)) {
        cout << line << endl;
    }
    infile.close();

    return 0;
}

Binary Streams

Binary streams are used to read and write binary data, which is data stored in a specific binary format. They are often used for files like images, audio, and executable files.

Key Points about Binary Streams:

  • Byte-Oriented: Binary streams operate on bytes, which are the smallest unit of data in a computer.

  • Unformatted I/O: You typically use unformatted I/O functions like read() and write() to work with binary data.

  • No Newline Character: Binary data doesn't have a specific newline character.


Example:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // Writing binary data to a file
    ofstream outfile("binary.bin", ios::binary);
    int data = 42;
    outfile.write(reinterpret_cast<char*>(&data), sizeof(data));
    outfile.close();

    // Reading binary data from a file
    ifstream infile("binary.bin", ios::binary);
    int read_data;
    infile.read(reinterpret_cast<char*>(&read_data), sizeof(read_data));
    cout << "Read data: " << read_data << endl;
    infile.close();

    return 0;
}

Choosing the Right Stream

  • Text Streams: Use text streams for human-readable data that can be easily edited and viewed.

  • Binary Streams: Use binary streams for data that needs to be preserved in its exact binary format, such as images, audio, or executable files.


By understanding the differences between text and binary streams, you can effectively work with various file formats in your C++ programs.

4 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page