Kachinsky
Kachinsky

Reputation: 573

Ifstream with a char array

How can I do this? I am using Visual Studio 2010 C++.

char * Buffer = new char[Filesize];
//Fill it with data here

std::ifstream BinaryParse(Buffer, std::ios::binary);
if(BinaryParse.is_open())
{
   BinaryParse.read((char*)&Count, sizeof(unsigned int));
}

That does not work. How can I make an ifstream behave in the same way as if it is reading a file, except reading from a char array?

Upvotes: 0

Views: 2263

Answers (1)

Yang
Yang

Reputation: 8180

You can try istringstream, which uses a C++ string as the input stream.

Here is an example from C++ reference:

// using istringstream constructors.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main () {
  int n,val;
  string stringvalues;

  stringvalues = "125 320 512 750 333";
  istringstream iss (stringvalues,istringstream::in);

  for (n=0; n<5; n++) {
    iss >> val;
    cout << val*2 << endl;
  }

  return 0;
}

You can find another example here: http://www.fredosaurus.com/notes-cpp/strings/stringstream-example.html.

Upvotes: 1

Related Questions