C++ istream::read() function



The C++ std::istream::read() function is used to read a specified number of characters from an input stream into a buffer. It is commonly employed for binary input operations. This function takes two arguments: a pointer to the buffer where data will be stored and the number of characters to read.

Syntax

Following is the syntax for std::istream::read() function.

 istream& read (char* s, streamsize n); 

Parameters

  • n − It indicates the number of characters to extract.
  • s − It indicates the pointer to an array where the extracted characters are stored.

Return Value

This function returns the basic_istream object (*this).

Exceptions

If an exception is thrown, the object is in a valid state.

Data races

Modifies the elements in the array pointed by s and the stream object.

Example

In the following example, where we are going to consider the basic usage of read() function.

 #include <iostream> #include <sstream> int main() { std::istringstream a("Hi, Namaste"); char b[6]; a.read(b, 2); b[2] = '\0'; std::cout << "Result : " << b << std::endl; return 0; } 

Output

Following is the output of the above code −

 Result : Hi 

Example

Consider the following example, where we are going to read the 4-byte integer from the integer stream.

 #include <iostream> #include <sstream> int main() { std::istringstream x("\x11\x10\x00\01"); int a; x.read(reinterpret_cast<char*>(&a), sizeof(a)); std::cout << "Result : " << a << std::endl; return 0; } 

Output

If we run the above code it will generate the following output −

 Result : 4113 
istream.htm
Advertisements