Move fopen to the outside of the loop, test if the file was successfully opened, then enter the loop. And lastly, close the file before returning.