Problem writing to SD card

The first thing to do is get rid of String and use C-style null terminated character arrays instead.
There is a known problem with the String library, on top of which there's only 2kB of Ram in total which is not enough to support the sort of memory usage that the String library requires.
You are also doing something really strange with nested while loops but fix the strings first.

Pete