C (clang), -DZ=lseek(d,0
+ 139 = 152 bytes
g,j,x,d,s,i,c;f(n){x=0;d=open(n,2);s=Z,2);for(j=2;j--;x++){Z,0);for(i=s;i--;write(d,&x,1));Z,0);for(i=s;i--;read(d,&c,1),c!=x&&x--&&j--);}}
Takes the filename as an argument
Ungolfed:
#import<fcntl#include <unistd.h>
int g,j,x,d,s,i,c;
void f(char*n){
x=0; /*Byte to write*/
d=open(n,O_RDWR);
s=lseek(d,0,SEEK_END); /*Get size of file*/
j=0;
for(j=0;j<2;j++){
/*Write Pass*/
lseek(d,0,SEEK_SET); /*Start writing from start of file*/
for(i=0;i<s;i++){
write(d,&x,1);
}
/*Verification Pass*/
lseek(d,0,SEEK_SET);
for(i=0;i<s;i++){
read(d,&c,1);
if(c!=x)x--,j--; /*If verification fails, repeat loop with the same value*/
}
x++;
}
}