Datalogging telnet session to sdcard

will you please tell me what to do here

No, but I'll make you think. If you are to put all the mail that arrives for your neighbor in a box for the time he is on vacation, when do you get the box (open the file)? When do you tape the box up (close the file)?

BEFORE you write ANY code, you should write some comments that show that you have thought about the correct order of events.

// Is there a client with data?

// Open the file

// Read each character from the client, and write it to the file

// Close the file

Now, figure out where to put these comments in your code, and you'll see what the problem is, and what the solution is.