>filename = strcat(filename, ".csv");
1. You're using gets()
2. Your buffer is too small
3. You append data with no regard to the size of the buffer.