C++ provides a set of unformatted I/O functions for reading and writing characters to streams. These functions are often used for low-level input and output operations, especially when dealing with binary data.
Key Unformatted I/O Functions
put():
Writes a single character to an output stream.
Syntax: ostream& put(char ch);
get():
Reads a single character from an input stream.
Syntax: istream& get(char& ch);
getline():
Reads a line of text from an input stream, up to a specified delimiter (usually a newline character).
Syntax: istream& getline(istream& is, string& str, char delim = '\n');
write():
Writes a block of characters to an output stream.
Syntax: ostream& write(const char* buffer, streamsize count);
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a file
ofstream outfile("output.txt");
outfile.put('H');
outfile.put('e');
outfile.put('l');
outfile.put('l');
outfile.put('o');
outfile.put('\n');
outfile.close();
// Reading from a file
ifstream infile("output.txt");
char ch;
while (infile.get(ch)) {
cout << ch;
}
cout << endl;
infile.close();
// Using getline()
ifstream infile2("input.txt");
string line;
while (getline(infile2, line)) {
cout << line << endl;
}
infile2.close();
// Using write()
ofstream outfile3("binary.bin", ios::binary);
char data[] = "Hello, binary world!";
outfile3.write(data, sizeof(data));
outfile3.close();
return 0;
}
Key Points:
Unformatted I/O provides more granular control over input and output operations.
put() and get() are used for character-level I/O.
getline() is useful for reading lines of text.
write() is used for writing binary data.
Error Handling: Always check for errors using functions like fail(), bad(), and eof().
While unformatted I/O functions offer flexibility, formatted I/O functions (using << and >> operators) are often preferred for their simplicity and readability in many common scenarios.
Comments