Subtracting histograms and saving to file

So, I’m trying to open a file “file.root” containing two histograms “h1” and “h2”. Then, I want to create a new histogram “h3”, such as h3 = h1 - coef * h2, where “coef” is a constant (Double_t). Finally, I want to save this new histogram “h3” in the file “file.root”.
My code is the following:

TFile *f = new TFile("file.root","RECREATE"); TH1F *h3 = (TH1F*)f->Get("h1"); h3->Add(h2,-coef); f->Write; f->Close;

I guess I’m making some obvious mistake somewhere, since “h3” is not actually written to “file.root”, and replaces “h1” (“h1” takes the values expected of “h3”, i.e. h1->h1-coef*h2).
Can someone point out my mistake?
Thanks.

TFile *f = new TFile("file.root", "UPDATE"); TH1F *h3 = (TH1F*)((f->Get("h1"))->Clone("h3")); Note that after each “f->Write();” a new "[url=https://root-forum.cern.ch/t/aux-1-aux-2-aux3/13345/1 of your “h1” and “h2” histograms will be created and written to your file, too.

A better way would be something like (no new spurious "[url=https://root-forum.cern.ch/t/aux-1-aux-2-aux3/13345/1 [code]TFile *f = new TFile(“file.root”, “UPDATE”);
TH1F *h1; f->GetObject(“h1”, h1);
if (h1) h1->SetDirectory(gROOT); // (gROOT) or (0)
TH1F *h2; f->GetObject(“h2”, h2);
if (h2) h2->SetDirectory(gROOT); // (gROOT) or (0)
TH1F h3 = (TH1F)(h1 ? h1->Clone(“h3”) : 0);
if (h2 && h3) h3->Add(h2, -coef);
if (h3) h3->Write();
delete f; // automatically deletes "h3"
delete h1;
delete h2;[/code] or even better: TFile *f = new TFile("file.root", "UPDATE"); TH1F *h2; f->GetObject("h2", h2); if (h2) h2->SetDirectory(gROOT); // (gROOT) or (0) TH1F *h3; f->GetObject("h1", h3); if (h3) { h3->SetName("h3"); // h3->SetTitle("h3 = h1 - coef * h2"); if (h2) h3->Add(h2, -coef); h3->Write(); } delete f; // automatically deletes "h3" delete h2;

Thanks! Worked like a charm.
Can I ask why it worked, though? Why did my method do the operations, but did not create the TKEY in the output file? How does the use of a clone solve that problem?

Your original macro could NOT have worked at all.
The first line:
TFile *f = new TFile(“file.root”,“RECREATE”);
unconditionally destroys the contents of your “file.root”, so there are NO “h1” nor “h2” inside any more.

P.S. See my improved macro in the end of my previous reply above.