如何用c语言,curl,cjson获取codeforces api
时间: 2024-06-11 12:07:47 浏览: 160
基于C语言的curl网络请求命令行工具设计源码
Codeforces API提供了RESTful API,可以使用curl和cjson库来获取API数据。以下是一个示例程序,该程序使用curl和cjson库来获取Codeforces API数据:
```c
#include <stdio.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#define API_URL "https://codeforces.com/api/user.rating?handle="
struct MemoryStruct {
char *memory;
size_t size;
};
// 回调函数,用于处理curl获取到的数据
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main(int argc, char **argv) {
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
if (argc < 2) {
printf("Usage: %s <handle>\n", argv[0]);
exit(1);
}
char url[1024];
snprintf(url, sizeof(url), "%s%s", API_URL, argv[1]);
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
res = curl_easy_perform(curl_handle);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
exit(1);
}
curl_easy_cleanup(curl_handle);
cJSON *json = cJSON_Parse(chunk.memory);
if (json == NULL) {
printf("Error parsing JSON data.\n");
exit(1);
}
cJSON *result = cJSON_GetObjectItemCaseSensitive(json, "result");
if (cJSON_IsArray(result)) {
int count = cJSON_GetArraySize(result);
for (int i = 0; i < count; i++) {
cJSON *item = cJSON_GetArrayItem(result, i);
cJSON *contestId = cJSON_GetObjectItemCaseSensitive(item, "contestId");
cJSON *contestName = cJSON_GetObjectItemCaseSensitive(item, "contestName");
cJSON *rank = cJSON_GetObjectItemCaseSensitive(item, "rank");
cJSON *ratingChange = cJSON_GetObjectItemCaseSensitive(item, "newRating") - cJSON_GetObjectItemCaseSensitive(item, "oldRating");
printf("Contest %d: %s (Rank: %d, Rating Change: %d)\n", contestId->valueint, contestName->valuestring, rank->valueint, ratingChange->valueint);
}
}
cJSON_Delete(json);
free(chunk.memory);
return 0;
}
```
这个程序会获取指定Codeforces用户的比赛评级历史记录,并输出到控制台上。你可以根据自己的需要修改代码,以便访问不同的Codeforces API端点和处理不同的数据。
阅读全文