Fix file io when opening files with write flag