Error in <TFile::WriteTObject>: Directory testHistos.root is not writable

I try to save a canvas to a root tree:

	TFile rootfile("testHistos.root","new");
	/* more code */;
	TCanvas* c1 = new TCanvas();
	TH1D* h1 = new TH1D("ref","ref",1000,0,4000);
	for (int ev=0;ev<par.N;ev++){
        	value = /*...*/

but when I run this i get the error

Error in TFile::WriteTObject: Directory testHistos.root is not writable

I am sure that I have write access in that directory as I am writing other files in the same code. What could be the problem?

Also I wonder how to do the following:

In the same code I have functions that fill and display some histograms that I also want to save to the same file, but I dont know how to do it. It looks something like this:

    void FillAndDrawHistograms(Data d){ /*... */ }
    void thisIsMyMainFunction() {
    	TFile rootfile("testHistos.root","new");

Do i have to pass the file to the function? Or can I simply call histogram->Write() inside that function and it will be written to the file?

TFile rootfile(“testHistos.root”, “recreate”);

yes that made it work. :slight_smile:

And for the second part of the question, seems to be fine to simply call h->Write() inside the function.

Well, I was to fast …

If the file already exists, then “recreate” lets me write, however it seems that it does not recreate the file, but after running my code for the second time I had a histogram twice in the file.
If the file does not exists and I use “recreate” I get the same error as mentioned above.

So my question remains, how do I correctly open a file for writing histograms?
If the file does not exist it should be created for writing, if it exists it should be overwritten (not content added).

If, without “recreating” the ROOT file, you call “histogram->Write();” multiple times, or if you also somewhere call “rootfile.Write();”, then you will have multiple versions / instances of your “histogram” stored (which in ROOT are called “cycles”).