MistyD
MistyD

Reputation: 17223

Writing data received from a socket to a file in C++

I am currently receiving data from a windows computer to a linux system which has the following implementation. It reads the data and writes it to a file

char buffer[4096];   
int BUFSIZE=4096; 
std::ofstream file(INPUT_PS_FILE_NAME, std::ios::out|std::ios::binary);
while (bytes_read > 0)
{
     buffer[bytes_read] = 0; 
     bytes_read = recv(newsockfd, buffer, BUFSIZE - 1, 0);  
     if(bytes_read>0) {
         file.write(buffer,BUFSIZE-1); 
         printf("Buffer: %s\n", buffer); 
     }
}

Now sometimes in my file I would get a whole bunch of "\00\00\00\00\00..." in my file and sometimes its fine but never on the console of the machine.My understanding is this happens because printf when passed an array will print all the contents of an array until it meets a null character however file.write does not. Please let me know if my understanding is correct. Also inorder to resolve this issue is there a way for me to have file.write behave like printf where it only prints until a NULL termination is found ?

Upvotes: 0

Views: 2408

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595402

You are using a while loop that checks bytes_read before recv() has been called for the first time. Use a do/while loop instead. And you are not outputting the read data correctly, either. You need to take bytes_read into account when outputting the data. You are writing too many bytes to file, and not null-terminating the buffer for printf().

Try this instead:

char buffer[4096];   
std::ofstream file(INPUT_PS_FILE_NAME, std::ios::out|std::ios::binary);
do
{
     bytes_read = recv(newsockfd, buffer, sizeof(buffer), 0);  
     if (bytes_read > 0) {
         file.write(buffer, bytes_read); 
         printf("Buffer: %.*s\n", bytes_read, buffer); 
         //or: printf("Buffer: %*.*s\n", bytes_read, bytes_read, buffer); 
     }
}
while (bytes_read > 0);

Upvotes: 2

Amit
Amit

Reputation: 46323

Your understanding is correct. printf (and all is variants) write formatted text to the output stream till a NULL character (\0) is found in the format string, and string parameters (%s) follow the same logic. write in the other hand deals with bytes and "ignores" what the values are. It will write NULLs without distinction.

If you want to write formatted text to a file, use fprintf.

Upvotes: 1

Related Questions