A potential problem with your code was that it leaves open a whole bunch of file descriptors (about 22,001) because you didn't close <B>, while it only has to have 2 open file descriptors at a time. Most OSs (all?) have a maximum amount of file descriptors that can be open at a given time.
Hope this helps avoiding this the next time.