- learn to use <p> and <code>
- get used to doing open ... or die (hint: open sometimes doesn't work)
- testing -z while you have the file open is likely to give a random result (you have no idea how long it's going to actually take to write the file; nothing is even remotely guaranteed until you close, and sometimes not even then; depending on your OS you may have to do a sync after closing. More likely you need to be doing Something Completely Different.)
That's all I can tell right now until you format your code better.