fix possible buffer overrun and memory leak

Use snprintf instead of sprintf and fclose() before return.

Change-Id: I3ed193464cc0dc90e9935ae19162667ad367628b