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);