|
| 1 | +#include<stdio.h> |
| 2 | +#include<curl/curl.h> |
| 3 | +#include<json-c/json.h> |
| 4 | +#include<string.h> |
| 5 | + |
| 6 | +// Callback function to handle API response. |
| 7 | +static size_t write_callback(char *contents, size_t size, size_t nmemb, void *userp) |
| 8 | +{ |
| 9 | + // Json objects to parse response. |
| 10 | + json_object *parsed_json, *main_data, *temp, *wind, *wind_speed, *humidity; |
| 11 | + |
| 12 | + // Tokenise JSON |
| 13 | + parsed_json = json_tokener_parse(contents); |
| 14 | + |
| 15 | + // Extract data from JSON response. |
| 16 | + json_object_object_get_ex(parsed_json, "main", &main_data); |
| 17 | + json_object_object_get_ex(main_data, "temp", &temp); |
| 18 | + json_object_object_get_ex(main_data, "humidity", &humidity); |
| 19 | + json_object_object_get_ex(parsed_json, "wind", &wind); |
| 20 | + json_object_object_get_ex(wind, "speed", &wind_speed); |
| 21 | + |
| 22 | + // Print json response with color. |
| 23 | + printf("\033[93mTemperature: %s°C\033[0m\n", json_object_get_string(temp)); |
| 24 | + printf("\033[93mHumidity : %s%%\033[0m\n", json_object_get_string(humidity)); |
| 25 | + printf("\033[93mWind Speed : %sknots\033[0m\n", json_object_get_string(wind_speed)); |
| 26 | + |
| 27 | + // return size of the data handled. |
| 28 | + return size * nmemb; |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | +int main(int argc, char **argv) |
| 33 | +{ |
| 34 | + // Define necessary variables. |
| 35 | + char *location = argv[1]; |
| 36 | + char key[64], url[1024]; |
| 37 | + |
| 38 | + // Initialise CURL structures. |
| 39 | + CURL *curl; |
| 40 | + CURLcode res; |
| 41 | + |
| 42 | + // Open key file to extract API key. |
| 43 | + FILE *fp = fopen("key", "r"); |
| 44 | + if(fp == NULL) |
| 45 | + { |
| 46 | + fprintf(stderr, "Unable to open `key` file."); |
| 47 | + exit(1); |
| 48 | + } |
| 49 | + fgets(key, 64, fp); |
| 50 | + fclose(fp); |
| 51 | + |
| 52 | + // Formulate the API endpoint. |
| 53 | + sprintf(url, "https://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&appid=%s", location, key); |
| 54 | + |
| 55 | + printf("\033[92mWeather details for %s:\n", location); |
| 56 | + |
| 57 | + // Perform a GET HTTP request. |
| 58 | + curl = curl_easy_init(); |
| 59 | + if(curl) |
| 60 | + { |
| 61 | + // Set CURL options |
| 62 | + curl_easy_setopt(curl, CURLOPT_URL, url); |
| 63 | + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); |
| 64 | + |
| 65 | + // Perform the request, res will get the return code |
| 66 | + res = curl_easy_perform(curl); |
| 67 | + /* Check for errors */ |
| 68 | + if(res != CURLE_OK) |
| 69 | + fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); |
| 70 | + |
| 71 | + // cleanup |
| 72 | + curl_easy_cleanup(curl); |
| 73 | + } |
| 74 | + |
| 75 | + return 0; |
| 76 | +} |
0 commit comments