In fact, we don't even need to keep track of which configurations we've seen. If they're going to meet, they're going to meet in fewer than 160,000 steps. Otherwise, they have to repeat some configuration, in which case they'll never meet.
for(i=0; i<160000 && (cowx != johnx || cowy != johny); i++) {
move(&cowx, &cowy, &cowdir);
move(&johnx, &johny, &johndir);
}
if(cowx == johnx && cowy == johny)
fprintf(fout, "%d\n", i);
else
fprintf(fout, "0\n");