The GNU C++ Iostream Library - Backing Up

Node: Backing Up Next: Indirectbuf Prev: Procbuf Up: Streambuf

Backing up

The gnu iostream library allows you to ask a streambuf to remember the current position. This allows you to go back to this position later, after reading further. You can back up arbitrary amounts, even on unbuffered files or multiple buffers' worth, as long as you tell the library in advance. This unbounded backup is very useful for scanning and parsing applications. This example shows a typical scenario:

	// Read either "dog", "hound", or "hounddog".
	// If "dog" is found, return 1.
	// If "hound" is found, return 2.
	// If "hounddog" is found, return 3.
	// If none of these are found, return -1.
	int my_scan(streambuf* sb)
	{
	    streammarker fence(sb);
	    char buffer[20];
	    // Try reading "hounddog":
	    if (sb->sgetn(buffer, 8) == 8
	        && strncmp(buffer, "hounddog", 8) == 0)
	      return 3;
	    // No, no "hounddog":  Back up to 'fence'
	    sb->seekmark(fence); // 
	    // ... and try reading "dog":
	    if (sb->sgetn(buffer, 3) == 3
	        && strncmp(buffer, "dog", 3) == 0)
	      return 1;
	    // No, no "dog" either:  Back up to 'fence'
	    sb->seekmark(fence); // 
	    // ... and try reading "hound":
	    if (sb->sgetn(buffer, 5) == 5
	        && strncmp(buffer, "hound", 5) == 0)
	      return 2;
	    // No, no "hound" either:  Back up and signal failure.
	    sb->seekmark(fence); // Backup to 'fence'
	    return -1;
	}

Constructor streammarker::streammarker (streambuf* sbuf)
Create a streammarker associated with sbuf that remembers the current position of the get pointer.

Method int streammarker::delta (streammarker& mark2)
Return the difference between the get positions corresponding to *this and mark2 (which must point into the same streambuffer as this ).

Method int streammarker::delta ()
Return the position relative to the streambuffer's current get position.

Method int streambuf::seekmark (streammarker& mark)
Move the get pointer to where it (logically) was when mark was constructed.


Next: Indirectbuf Up: Streambuf