# [C (clang)], `-DZ=lseek(d,0` + 139 = 152 bytes

<!-- language-all: lang-c -->

    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--);}}

[Try it online!][TIO-jnuko05c]

[C (clang)]: http://clang.llvm.org/
[TIO-jnuko05c]: https://tio.run/##lY/Ba4MwGMXP7V@ReZCEfpnOa8igq54GG7SDgZciSbSxGsVkLEP81@csPQy6007v4/3e9@AJKprCVPNcQQ0eJFjQIFiJDRk9j5nkXa8MNpAQZnl@kbIbcM0TVlPK/GZDxhziq6u5ZXpxPwftFJYQengghP3hgyrkBYsFg7jjPgw9pWG4NBI2TXMUvR736fueJ3DIsufjIXvj8fXMXlKerLVxqC20wWRcrVf2yzrV4kCJU4e2Tzv0iCLX9lFx77wLCPtNnJSXH22P6O42UeLgvz/T/C3KpqjsTNOcN1ap8zIq/gE "C (clang) – Try It Online"

Takes the filename as an argument

Ungolfed:
<pre><code>#include &lt;unistd.h&gt;
int g,j,x,d,s,i,c;
void f(char*n){
&#9;x=0; /*Byte to write*/
&#9;d=open(n,O_RDWR);
&#9;s=lseek(d,0,SEEK_END); /*Get size of file*/
&#9;j=0;
&#9;for(j=0;j&lt;2;j++){
&#9;&#9;/*Write Pass*/
&#9;&#9;lseek(d,0,SEEK_SET); /*Start writing from start of file*/
&#9;&#9;for(i=0;i&lt;s;i++){
&#9;&#9;&#9;write(d,&amp;x,1);
&#9;&#9;}
&#9;&#9;
&#9;&#9;/*Verification Pass*/
&#9;&#9;lseek(d,0,SEEK_SET);
&#9;&#9;for(i=0;i&lt;s;i++){
&#9;&#9;&#9;read(d,&amp;c,1);
&#9;&#9;&#9;if(c!=x)x--,j--; /*If verification fails, repeat loop with the same value*/
&#9;&#9;}
&#9;&#9;x++;
&#9;}
}
</code></pre>