简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM