-2

I'm building a ftp server and this is a message sent from the client to the server to check whether the file size is approved by the server. I need to use char* in function write so I want to convert string to char*. The string structure is fileName#fileSize(test.txt#37). I tried c_str but got rubbish in the end.

Let have a look at the following code:

string str(filenameDes);
str += HASHTAG;
str += to_string(fileSize);
cout << "str: " << str << endl;
char * pchar = str.c_str();
// sending file size to server
int retVal = write(socket, pchar, strlen(pchar));

Although when i want to print the message in the server using cout i get this output: test2#37�� or something close to it, meaning i get rubbish in the end.

How do i clean the rubbish? or any other command to convert to char* ?

itzikos
  • 375
  • 1
  • 5
  • 13

1 Answers1

0

The problem was that when i received the message with array of char i didn't initailize it with \0 in all of the cells. This solves the case when you dont know which length of message you're gonna get. Thanks a lot to PaulMcKenzie.

itzikos
  • 375
  • 1
  • 5
  • 13
  • You don't have to initialize *all* data to zero, just terminate the buffer correctly. The `recv` (or `read`) call do return the length of the data received, just do e.g. `buffer[returnOfRecv] = '\0'`. – Some programmer dude Jun 06 '15 at 12:03
  • Warning to future: This works for an ftp server because the protocol stops and waits for a response. It will not work if multiple messages can be sent without waiting because multiple messages may wind up in the same call to `recv`. There is no way to tell them apart without extra information. – user4581301 Jun 06 '15 at 15:01