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 memory
- {
- char *response;
- size_t size;
- };
- static size_t func(void *data, size_t size, size_t nmemb, void *userp)
- {
- size_t realsize = size * nmemb;
- struct memory *mem = (struct memory *)userp;
- char *ptr = realloc(mem->response, mem->size + realsize + 1);
- if(!ptr)
- {
- fputs("Failed Memory\n", stdout);
- return EXIT_FAILURE;
- }
- mem->response = ptr;
- memcpy(&(mem->response[mem->size]), data, realsize);
- mem->size += realsize;
- mem->response[mem->size] = 0;
- return realsize;
- }
- 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]);
- const char *name = json_object_get_string(j[4]);
- printf("%s\n", name);
- }
- int main(void)
- {
- struct memory 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