I want to store different types of variables into a buffer to a char array so that I can send it and when the server receives it I want to take that formatted buffer and get the variables back.
I have found 0 examples of how to make this work, everyone makes it look as such a simple task that they do not provide the output, so I tried it for myself.
I've made a dumb program where I store and extract without even sending, to get used to formats and avoid all the problems I've read about buffer overflow and whatnot.
int main(int argc, char * argv[]) {
int op = 1; //1 porque es un alta
int pid = getpid();
printf("pid %d\n", pid);
char * tema = argv[1];
printf("Tema %s\n", tema);
int longitud = strlen(tema) + sizeof(int) * 2 + 1;
/
printf("longitud %d\n", longitud);
char mensaje[longitud];
char * ptr = mensaje;
snprintf(ptr, longitud, "%d %d %s", op, pid, tema);
printf("mensaje %s\n", mensaje);
int opRecibido = 0;
int pidRecibido = 0;
char * temaRecibido;
sscanf(mensaje, "%d %d %s", & opRecibido, & pidRecibido, temaRecibido);
printf("temaRecibido %s\n", temaRecibido);
printf("pidRecibido %d\n", pidRecibido);
printf("opRecibido %d\n", opRecibido);
}
Of course I've tried several iterations of this. I can't get it right. temaRecibido either writes null, or segfault, or nothing works, etc.
Again, I want this as a way to serialize my data before sending it from a TCP client to a server, but I can't even make this work, without sending it.
The part that does not work is the sscanf. I've read about everything I've found googling it specially
Since we have snprintf, why we don't have a snscanf?
and
How to send formatted string to socket using a small buffer?
But there's something I'm clearly missing
Edit: And since I'm at it, and I see so many comments and blogs telling me not to use sscanf, please what would be the proper way of solving this stance? Because every single example I see works with 1 or 2 char* and it's simply not helping me