Maybe, you have to write the values of the position first into an array and copy it later from the array into the file, because writing into a a file is quite slow.