Return an error, not crash, when file cannot be opened

replace_file will crash if the file cannot be opened, this
makes it so it returns an error instead