-
Notifications
You must be signed in to change notification settings - Fork 0
C Example Code
MMDRZA edited this page Oct 18, 2024
·
1 revision
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
// Structure to store cryptocurrency data
struct Coin {
char symbol[10];
char lastPrice[20];
char highPrice24h[20];
char lowPrice24h[20];
char changeRate[10];
char lastUpdated[30];
};
// Structure to store the response
struct Memory {
char *response;
size_t size;
};
// Callback function for curl to write data
static size_t write_callback(void *contents, 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 == NULL) {
printf("Not enough memory (realloc returned NULL)\n");
return 0;
}
mem->response = ptr;
memcpy(&(mem->response[mem->size]), contents, realsize);
mem->size += realsize;
mem->response[mem->size] = 0;
return realsize;
}
// Function to fetch cryptocurrency data
void fetch_crypto_data() {
CURL *curl;
CURLcode res;
// Initialize the memory structure
struct Memory chunk = {0};
// Initialize curl
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
// Set the URL
curl_easy_setopt(curl, CURLOPT_URL, "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json");
// Set the write callback function
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
// Set the memory chunk as the user pointer
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
// Perform the request
res = curl_easy_perform(curl);
// Check for errors
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
// Here you would parse the JSON response (if you had a proper JSON parser in C)
// Currently, this will just print the response directly for simplicity.
printf("%s\n", chunk.response);
}
// Cleanup
curl_easy_cleanup(curl);
free(chunk.response);
}
curl_global_cleanup();
}
int main(void) {
fetch_crypto_data();
return 0;
}
👨💻 Programmer : PyMmdrza 🌍 Official Website Mmdrza.Com 📧 Email : [email protected]
📧 [email protected]