writeToFile function: fix crash and maybe CTD (can't reproduce) due to paths containing file name only. #21