Use freopen() rather than fclose();fopen()