user3302936
user3302936

Reputation: 45

How to store data from a file read in binary mode C++

Hi i am trying to read a file , say for example 'sample.txt', in binary mode-c++ and i need to store the file text (eg."nodeA nodeB") in a vector . eg: "A A B E A B G" if this is what is in the text file , i want to read it in binary form and then store it in some variable and then do some operations to it . Any help would be appreciated. So far i have got is :

int main () {
  streampos begin,end;
  ifstream myfile ("example.bin", ios::binary);
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}

The text part in the file myfile can be got how ?

Upvotes: 1

Views: 1658

Answers (2)

Mike Kinghan
Mike Kinghan

Reputation: 61550

Your file sample.txt, or whatever, is a text file. I believe you want to "read it in binary form" because you think that you have to do that in order to find out the size of the data, so that you can then allocate storage of that size, in some variable, to contain the data.

In that case, really all you want to do is read a text file into a suitable variable, and you can do this very simply, without having to discover the length of the file:

#include <fstream>
#include <iterator>
#include <string>
#include <algorithm>

...

std::istream_iterator<char> eos; // An end-of-stream iterator
// Open your file
std::ifstream in("sample.txt"); 
if (!in) { // It didn't open for some reason.
    // So handle the error somehow and get out of here. 
}
// Your file opened OK
std::noskipws(in);  // You don't want to ignore whitespace when reading it
std::istream_iterator<char> in_iter(in); // An input-stream iterator for `in` 
std::string data;   // A string to store the data
std::copy(in_iter,eos,std::back_inserter(data)); // Copy the file to string

Now, the whole contents of sample.txt are in the string data and you can parse it anyway you want. You could replace std::string with some other standard container type of char, e.g. std::vector<char>, and this would work just the same.

Upvotes: 1

halfflat
halfflat

Reputation: 1584

The method you are after is ifstream::read(char *,streamsize). Having gotten the size of the file in bytes, you can read the data into a vector<char> of the correct size (after seeking back to the beginning of the file):

streamsize n=end-begin;
vector<char> data((size_t)n);

myfile.seekg(0,ios::beg);
myfile.read(&data[0],n);

The iterator type of vector<char> may not necessarily be a char * pointer, so instead we pass as the first argument to read a pointer to the first element of the vector. The elements of a std::vector are guaranteed to be laid out contiguously, and so we can be assured that writing to &data[0]+k is equivalent to &data[k], for valid indices k.

Upvotes: 3

Related Questions