public member function
<streambuf> <iostream>

std::streambuf::sgetn

streamsize sgetn (char* s, streamsize n);
Get sequence of characters
Calls the protected virtual member xsgetn with the same arguments s and n.

The default definition of xsgetn in streambuf retrieves characters from the controlled input sequence and stores them in the array pointed by s, until either n characters have been extracted or the end of the sequence is reached.

Parameters

s
Pointer to an array where the character sequence is copied.
n
Maximum number of characters to be retrieved.
This shall be a non-negative value.
streamsize is a signed integral type.

Return Value

The number of characters copied.
streamsize is a signed integral type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// read a file into buffer - sgetn() example
#include <iostream>     // std::cout, std::streambuf, std::streamsize
#include <fstream>      // std::ifstream

int main () {
  char* contents;
  std::ifstream istr ("test.txt");

  if (istr) {
    std::streambuf * pbuf = istr.rdbuf();
    std::streamsize size = pbuf->pubseekoff(0,istr.end);
    pbuf->pubseekoff(0,istr.beg);       // rewind
    contents = new char [size];
    pbuf->sgetn (contents,size);
    istr.close();
    std::cout.write (contents,size);
  }
  return 0;
}

This example reads an entire file into a buffer using its stream buffer, and is then written to the standard output.

Data races

Modifies up to all of the first n characters in the array pointed by s.
Modifies the stream buffer object.
Concurrent access to the same array or to the same stream buffer object may introduce data races.

Exception safety

Basic guarantee: if an exception is thrown, the stream buffer is in a valid state (this also applies to standard derived classes).

Invalid arguments cause undefined behavior.

See also