I try to send a structure from a client to a server. I read in the internet that i have to type cast the structure to a char array, but when i try this the char has not content.
Here is my struct:
struct packet
{
int pa_ID;
char message[MESSAGESIZE];
};
And here I try to send the struct:
int sendFile(FILE *file, SOCKET sock)
{
int amountToSend, amountSent;
int i = 0;
char buffer[BUFFERSIZE], serializedPacket[BUFFERSIZE];
while (!feof(file)) {
struct packet p;
fgets(p.message, MESSAGESIZE, file);
p.pa_ID = i;
if (p.message[strlen(p.message) - 1] == '\n')
p.message[strlen(p.message) - 1] = '\0';
amountToSend = sprintf_s(serializedPacket, sizeof(buffer), (char*)&p);
amountSent = send(sock, serializedPacket, amountToSend, 0);
if (amountSent == SOCKET_ERROR) {
fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
getchar();
WSACleanup();
return -1;
}
printf("Send %d bytes (out of %d bytes) of data: [%.*s]\n", amountSent, amountToSend, amountToSend, serializedPacket);
memset(buffer, 0, sizeof(buffer));
memset(p.message, 0, sizeof(p.message));
memset(&p, 0, sizeof(p));
i++;
}
fclose(file);
return 0;
}
The reading from the file functions without errors, but the serializedPack is just empty and I really dont see why.
Hope someone can help.
This:
doesn’t make any sense at all.
The third argument to
sprintf_s()is a formatting string, but you pass a pointer to a structure, re-cast as a character pointer. This makes absolutely no sense.Representing your structure as a textual string (serializing to string) might be a good idea, but then you need a proper formatting string:
Depending on how you send this, you might also want to include the 0-terminator for the string in the transmitted data.