Fix possible buffer overrun and memory leak

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

Credit: Sungmin Choi

Backported from VanirAOSP, kk44 branch
http://vaniraosp.goo.im/#/c/9380/1

Change-Id: Ib978dcae0d0b3755e7a4384b88c646775423bad6
Merge "Fix possible buffer overrun and memory leak" into gingerbread