The current directory (root) is not associated with a file error when looping over input files


ROOT Version: 6.18/00
Platform: Red Hat 8.5.0-16
Compiler: gcc version 8.5.0


Hello everyone, I am trying to loop over several root files to get some information and then dump all of it in one single tree in a separate root file. I am doing it with the following code:


	TSystemDirectory dir("/path/", "/path/");
	TList *files = dir.GetListOfFiles();

	out_file = TFile::Open("/path/detector_truth_all.root", "recreate");
	out_tree = new TTree("detections", "detections");

	std::vector<ROOT::Math::XYZVector> sp;
	out_tree->Branch("sp", &sp);
	
	// Loop over files
	if (files) {
		TSystemFile *file;
		TString fname;
		TIter next(files);
		while ((file = (TSystemFile*)next())) {
			fname = file->GetName();
			if (!file->IsDirectory() && fname.EndsWith(".root") && (fname != "detector_truth_all.root")) {
				auto f = TFile::Open(fname);
				if (!f) {
					std::cout << "Couldn't open file \n";
					f->Close();
					continue;
				}

				auto tree = (TTree*)f->Get("Events");
				if (!tree) {
					std::cout << "Didn't find the Event Tree. Invalid oaEvent file. \n";
					f->Close();
					continue;
                }
                for (size_t i = 0; i < tree->GetEntries(); ++i) {
				       // SOME CODE HERE //
                       out_tree->Fill(info);
				} // events
				f->Close();
			} // root files
		} // while
	} // files
	out_tree->Write();
	out_tree->Print();	
}

I get the following error:

Error in <TROOT::WriteTObject>: The current directory (root) is not associated with a file. The object (detections) has not been written.

I understand that I need to change something with the output file, but I don’t know how to fix it. Any help will be welcomed!

Note: I use this code by compiling it with g++ first and then running it.

Before “out_tree->Write();”, try to add: out_file->cd();

Unrelated improvement to your code:
Replace

auto tree = (TTree*)f->Get("Events");

with

auto tree = f->Get<TTree>("Events");

and

f->Close();

with

delete f;

To solve the issue you can also replace:

	out_tree->Write();

with

	out_file->Write();

Thanks a lot for the recommendations and the solution, works perfectly now!