What file type to save TFitResultPtr

I’m trying to write the fit parameters of a histogram to a file using TFitResultPtr as described in section 7.7.7 of this article. i.e.

TFitResultPtr r = hist->Fit(myFunction,"S");
TFile f("example.txt","create")
r->Write(); 

The article says that I can store the result in a file, but it doesn’t specify what kind of file I can store the result in. I’ve tried writing to a .txt file and a .dat file, but neither works. Printing r works just fine though. Can someone please help out?


Please read tips for efficient and successful posting and posting code

ROOT Version: 6.20.06
Platform: Windows 10
Compiler: Not Provided


Hi,
you need to write it into a ROOT file:

        TH1F* h1 = new TH1F("h1", "histo from a gaussian", 100, -3, 3);
        h1->FillRandom("gaus", 10000);

        TFitResultPtr r = h1->Fit("gaus", "S");
        h1->Draw();

        TFile* myFile = new TFile("myfile_04July2020.root", "RECREATE");
        r->Write();
        myFile->Close();

        delete h1; h1 = nullptr;
        delete myFile; myFile = nullptr;

1 Like

Thanks. I tried a root file before, but opening the file directly just showed a bunch of blank pages. However, reading it through Root worked. By any chance, is there a way to store the information as a plain text file?

Sure, you can do

r->Print()

having forwarded the stdout to a text file like that:

        TH1F* h1 = new TH1F("h1", "histo from a gaussian", 100, -3, 3);
        h1->FillRandom("gaus", 10000);

        TFitResultPtr r = h1->Fit("gaus", "S");
        h1->Draw();

        TFile* myFile = new TFile("myfile_04July2020.root", "RECREATE");
        r->Write();
        myFile->Close();

        fstream fs;
        fs.open("abcd.txt", ios::out);
        string lin;
// Make a backup of stream buffer
        streambuf* sb_cout = cout.rdbuf();
        streambuf* sb_cin = cin.rdbuf();
// Get the file stream buffer
        streambuf* sb_file = fs.rdbuf();
// Now cout will point to file
        cout.rdbuf(sb_file);
// everything printed after this line will go to the fs
        r->Print();
// get the previous buffer from backup
        cout.rdbuf(sb_cout);
// everything printed after this line will go to whereever it went before
        fs.close();
        delete h1;
        delete myFile;

1 Like