Writting and Getting a std::vector from a TFile


I’m trying to save a std::vector in a root file, and it looks like it is well saved (I don’t get any error), but I don’t know how to read it again.

I copy some code reproducing the error:

TFile fout;

std::vector<Double_t>  xx; // I create and fill the vector to be saved.
for( int k = 0; k <3; k++ ) xx.push_back(k);
fout.WriteObject(&xx,"xx"); // I store the vector in the TFile

TFile fin;
std::vector<Double_t>  *yy;
fin.GetObject("xx",yy); // I try to retrieve the vector

And this is the error I get:

Error in TFile::ReadBuffer: error reading all requested bytes from file TEST.root, got 214 of 300
Error in TFile::Init: TEST.root failed to read the file type data.

Thank you very much in advance for you help!


Try this way (TFile::Open() is a static method):

   TFile *fout = TFile::Open("TEST.root", "RECREATE");

   std::vector<Double_t> xx; // I create and fill the vector to be saved.
   for (int k = 0; k<3; k++) xx.push_back(k);
   fout->WriteObject(&xx, "xx"); // I store the vector in the TFile

   TFile *fin = TFile::Open("TEST.root", "READ");
   std::vector<Double_t> *yy;
   fin->GetObject("xx", yy); // I try to retrieve the vector
   for(std::vector<Double_t>::iterator it = yy->begin(); it != yy->end(); ++it) {
      std::cout << *it << '\n';

Cheers, Bertrand.

It works! Thank you!

I would prefer a way to write and retrieve to the same kind of class, instead to get it into a pointer. I mean to do something like:

std::vector<Double_t> yy;
fin->GetObject(“xx”, yy);

Instead of:

std::vector<Double_t> *yy;
fin->GetObject(“xx”, yy);

But the first doesn’t seems to be available.
Anyway like this is fine. Thanks again!


std::vector<Double_t> *tmp;
fin->GetObject("xx", tmp);
std::vector<Double_t> yy = *tmp;
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.