Writing to memory buffer first and then flusch to file at the end. Avoid accidental overwrites of previoulsy created files if input file is invalid.