Question: I have a binary file I want to transmit and basically I was wondering if I converted the c\_string into a string, whether that would have an effect on the end result, because I sent a c\_string after using read() and made sure it read for binary files and not text file, but then I put it in a string and converted back to c\_string. If that's no good, is there a simple way to get it back to binary form?

```
    FILE *file = fopen(filename, "ab");

    int size = 0;

    do{

        size = recvfrom(s, buffer, 128, 0, (LPSOCKADDR) &sa_in, &senderSize);

        if(size > 0)
        {

             fwrite(buffer, sizeof(char), size, file);

        }
    }while(size > 0);

```

c\_string(binary) turns into string and then turns back into c\_string.

```
            FILE *file = fopen(filename, "ab");

            int size = 0;

            do{

                size = recvfrom(s, buffer, 128, 0, (LPSOCKADDR) &sa_in, &senderSize);

                if(size > 0)
                {
                    string bufferstring(buffer);
                    strcpy(buffer, bufferstring);

                    fwrite(buffer, sizeof(char), size, file);

                }
            }while(size > 0);

```

Answer: 
Doing this:

```
string bufferstring(buffer);

```

means to use a null-terminated string as the input. The data in `buffer` is probably not a null-terminated string of exactly length 127. If it's shorter you have data loss, and if there is no null terminator in buffer then you cause undefined behaviour.

The next line, `strcpy(buffer, bufferstring);` doesn't even compile; `std::string` cannot be used as argument to `strcpy`.

After that you write from `buffera` which isn't even defined.

Was there some problem with your first version of code that makes you want to change it?
Binary data may have `NUL`s mixed in, so the line

```
string bufferstring(buffer);

```

may truncate the data. This line:

```
strcpy(buffer, bufferstring);

```

has the same problem of truncation, and also, you need to call `std::string::c_str()` to get the `char *` representation. Use `memcpy()` to avoid truncation.

Lastly, I don't like the do...while() pattern.

```
while((size = recvfrom(s, buffer, 128, 0, (LPSOCKADDR) &sa_in, &senderSize)) > 0) {
    string bufferstring(buffer, size);
    memcpy(buffer, bufferstring.c_str(), bufferstring.size());
    fwrite(buffer, sizeof(char), size, file);
}

```