문제

I am writing simple server - client app. On server side I receive char arrays of data (with const size). However last char array can have empty bytes.

I append recieved array to file in loop. Here is code:

char buffer[256];
/* ...  */
FILE *file;
file = fopen(file_name,"ab+");
for (i = 0; i < parts; ++i) {
    if ((length = recv(sockfd, buffer, 256, 0)) < 0) {
        /* recv failed  */
    }
    send(sockfd, "OK", 2, 0);
    fwrite(buffer, 1, 256, file);
}
fclose(file);

for example: ... Quisque dignissim turpis sapien, non facilisis risus gravida at. \00\00\00\00

Is there any way how to skip last \0 chars? Or do I have to copy last array byte by byte.

도움이 되었습니까?

해결책

Use

fwrite(buffer, 1, length, file);

This will only write as much characters as you acutally received. If the extra \0 are part of the packet it will be written, otherwise not.

If you are receiving the \0 characters as part of the packet but you don't want to write them, then you'd have to do this:

fwrite(buffer, 1, strlen(buffer), file);

다른 팁

If the return value of the recv function is the length of the readed bytes in the buffer, use that instead the buffer size in the fwrite call

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top