How to get particle energy in RunAction?

I wanto record the particle energy in EndOfRunAtion,
and here is endofrunaction:

// G4double P_Energy = fPrimary->GetParticleGun()->GetParticleEnergy();
// std::fstream file(“result.txt”, std::ios::app);
// file
// <<“this_energy”<<P_Energy
// <<G4endl;
//
// file.close();
But have this question:
Segmentation fault (Address not mapped to object [0x8])

Confused with this.Could someone have an advice?

switch to constructor and end in EndOfRunAction(…
std::ofstream file(…