Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <json.h>
- #include <curl/curl.h>
- struct request
- {
- char *response;
- size_t size;
- };
- static size_t func(void *data, size_t size, size_t nmemb, void *userp)
- {
- size_t size_p = size * nmemb;
- struct request *mem = (struct request *)userp;
- char *ptr = realloc(mem->response, mem->size + size_p + 1);
- if(!ptr)
- {
- fputs("Failed Memory\n", stdout);
- return EXIT_FAILURE;
- }
- mem->response = ptr;
- memcpy(&(mem->response[mem->size]), data, size_p);
- mem->size += size_p;
- mem->response[mem->size] = 0;
- return size_p;
- }
- void parse(char *buffer)
- {
- struct json_object *jobj;
- struct json_object *j[10];
- jobj = json_tokener_parse(buffer);
- size_t i;
- static char *keys[] = {"cep", "logradouro", "complemento",
- "bairro", "localidade", "uf",
- "ibge", "gia", "ddd", "siafi"};
- for(i = 0; i < 10; i++)
- json_object_object_get_ex(jobj, keys[i], &j[i]);
- for(i=0; i < 10; i++)
- {
- if(json_object_get_string(j[i]) != NULL)
- printf("%s\n", json_object_get_string(j[i]));
- else
- {
- fputs("Failed Json\n", stdout);
- goto exit;
- }
- }
- exit:
- json_object_put(jobj);
- }
- int main(void)
- {
- struct request s;
- s.response = malloc(1000);
- if(!s.response)
- {
- fputs("Failed Memory\n", stdout);
- return EXIT_FAILURE;
- }
- s.size = 0;
- fputs("Input your CEP: ", stdout);
- char cep[9];
- scanf("%9[^\n]s", cep);
- size_t i, j = 0;
- for(i = 0; cep[i]; i++)
- if(cep[i] >= '0' && cep[i] <= '9') j++;
- if(j == 8)
- {
- char url[50];
- snprintf(url, sizeof url, "http://viacep.com.br/ws/%s/json/", cep);
- CURL *curl = curl_easy_init();
- if(curl)
- {
- curl_easy_setopt(curl, CURLOPT_URL, url);
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, func);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&s);
- curl_easy_perform(curl);
- parse(s.response);
- curl_easy_cleanup(curl);
- } else {
- fputs("Request Failed\n", stdout);
- return EXIT_FAILURE;
- }
- } else {
- fputs("Invalid Number\n", stdout);
- }
- free(s.response);
- return 0;
- }
Add Comment
Please, Sign In to add comment