Some comments. First of all, I don't know what system you're using, but my Unix hosting account will wait on flock rather than returning an error if another flock is currently running. Second, it's very inconvenient to flock the file you're trying to process. What if you want to open a file, read its contents, close it, open it for writing, write some new or edited data, and close? If you're flocking the primary file, the flock will be gone between the first close and the second open. What you need to do instead is create a temporary file based off the name of the file you're trying to lock, lock that, do whatever processing needs to be done on the primary file, then unlock. This will give you much more flexibility. Thirdly, you shouldn't have your flock routine also be your open routine, and your f(un)lock be your close. Separate the processes so you don't have to change your routines every time you want to do something different to the files you're editing.
As for your code, any hints as to where you think the problem(s) lie?