Jump to content

streaming files

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
tootypegs

tootypegs

    Newbie

  • Members
  • Pip
  • 4 posts
Hi, would anyone be able to show me an example of how to use the stream.seek() function from c++. I would like to use this to stream through a file and retrieve the 11th and 12th byte but im having trouble implimenting it

any pointers or tips would be appreciated

thank you

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
There's two seek()-functions, one for reading file, and one for writing files. The one you're searching is of course the one for reading files, as you're trying to do so. You've to append a 'g' (get) to the function name ('p' (put) if you wanted to write to files), so the function you need is called seekg()
Here's an example of how to use it...
#include <iostream>
#include <fstream>

int main()
{
	std::ifstream stream("file.txt");

	if(stream.is_open())
	{
		char Byte11;
		char Byte12;

		stream.seekg(10);   // Seek to position 10
		stream.get(Byte11); // Read position 11
		stream.get(Byte12); // Read position 12
		
		std::cout << "11th byte: " << Byte11 << std::endl;
		std::cout << "12th byte: " << Byte12 << std::endl;

		stream.close();
	}
	else
		std::cout << "Unable to open file" << std::endl;

	return 0;
}