Reputation: 659
I'm working on restful client written in C. It is very simple, I just have to send by post a person name (John, Sam, Muhammad, Whatever...) which I write on terminal.
My whole code is working fine but I have some issues with conversion char or strings, to send by post.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
int main(void) {
CURL *curl;
CURLcode res;
int x = 1;
unsigned char m;
while (x != 0) {
printf("Opcao 1 para incluir nova pessoa\n");
printf("Opcao 2 para listar pessoas\n");
printf("Opcao 0 para sair\n");
printf("Selecione a opcao: ");
scanf("%d",&x);
if (x == 1) {
printf("Nome da pessoa: ");
scanf("%s",&m);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "localhost/wsRest/index.php/novo/" );
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
}
printf("\n");
}
curl_global_cleanup();
return 0;
}
I need to find a way to put the name written on variable 'm' in curl_easy_setopt() function, concatenated with my URL, but I have no idea how to do it, and the examples that a I found cant even read the URL to another variable...
How can I do it?
Thanks you everyone!
Upvotes: 1
Views: 62
Reputation: 21233
This won't work the way you expect:
scanf("%s", &m);
m
is an unsigned char
, the scanf %s
modifier will attempt to read a string, write it to the pointer you feed it, and null-terminate it. For any non-empty name, it will write to invalid memory (if you're lucky, this should crash).
Indeed, you passed a pointer to a character, but there's only space for 1 character.
You should use an array instead, for example:
char m[512];
/* ... */
scanf("%s", m);
Note that this places an upper bound of 511 on the name length. If you expect longer names, increase the buffer size.
UPDATE:
You can prepend the URL by doing:
char m[512];
int idx = sprintf(m, "localhost/wsRest/index.php/novo/");
/* ... */
scanf("%s", &m[idx]);
Then pass m
as the url.
This works by first storing the URL path in m
, and then reading the input string into the rest of the buffer. sprintf(3)
returns the number of characters written, so idx
is the offset of the first position after the URL path.
If you want to append instead, then scanf("%s", m)
and then use strcat(m, "localhost/wsRest/index.php/novo/")
.
Again, this assumes that the name + the URL size is less than 511.
Upvotes: 3
Reputation: 34839
First, you need an array to hold the name entered by the user. Change this
unsigned char m;
to this
char m[1000];
Next, you need an array to hold the URL
char url[1200];
Then you can use sprintf
to append the name to the URL
sprintf( url, "localhost/wsRest/index.php/novo/%s", m );
And finally pass the url
to the setopt
function
curl_easy_setopt(curl, CURLOPT_URL, url);
Upvotes: 1