initial commit

This commit is contained in:
SuperNovaa41 2025-02-24 15:04:53 -05:00
commit a42421a083
7 changed files with 139 additions and 0 deletions

24
Makefile Normal file
View File

@ -0,0 +1,24 @@
CC=gcc
CFLAGS= -c -g -Wall
LDLIBS = -lcurl
TARGET := isbn-lookup
BUILD_DIR := ./build
SRC_DIRS := ./src
SRCS := $(shell find $(SRC_DIRS) -name '*.c')
OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
$(BUILD_DIR)/$(TARGET): $(OBJS)
$(CC) $(OBJS) -o $@ $(LDLIBS)
$(BUILD_DIR)/%.c.o: %.c
mkdir -p $(dir $@)
$(CC) $(CFLAGS) -c $< -o $@
.PHONY: clean
clean:
rm -rf $(BUILD_DIR)

BIN
build/isbn-lookup Executable file

Binary file not shown.

BIN
build/src/curl.c.o Normal file

Binary file not shown.

BIN
build/src/main.c.o Normal file

Binary file not shown.

84
src/curl.c Normal file
View File

@ -0,0 +1,84 @@
#include <curl/curl.h>
#include <curl/easy.h>
#include <stdlib.h>
#include <string.h>
#include "include/curl.h"
#define API_URL "https://openlibrary.org/search.json?q="
#define API_URL_LEN 38
static void setup_api_link(const char* isbn, char** buf)
{
size_t buffer_len;
buffer_len = API_URL_LEN + strlen(isbn);
(*buf) = malloc(sizeof(char) * buffer_len);
strncpy((*buf), API_URL, API_URL_LEN + 1);
strncpy((*buf)+ API_URL_LEN, isbn, strlen(isbn));
(*buf)[buffer_len] = '\0';
}
#undef API_URL
#undef API_URL_LEN
static void init_get_response(get_response* buf)
{
buf->len = 0;
buf->buf = malloc(buf->len + 1);
if (!(buf->buf)) {
perror("malloc");
exit(EXIT_FAILURE);
}
buf->buf[0] = '\0';
}
void free_get_response(get_response* buf)
{
free(buf->buf);
}
static size_t curl_write_response(void* ptr, size_t size, size_t nmemb, get_response* buf)
{
size_t new_len = buf->len + (size * nmemb);
buf->buf = realloc(buf->buf, new_len + 1);
if (!(buf->buf)) {
perror("realloc");
exit(EXIT_FAILURE);
}
memcpy(buf->buf + buf->len, ptr, size * nmemb);
buf->buf[new_len] = '\0';
buf->len = new_len;
return size * nmemb;
}
CURLcode book_api_call(const char* isbn, get_response* buf)
{
CURL* handler;
CURLcode result;
char* request_url;
handler = curl_easy_init();
if (!handler) {
perror("curl_easy_init");
exit(EXIT_FAILURE);
}
setup_api_link(isbn, &request_url);
init_get_response(buf);
curl_easy_setopt(handler, CURLOPT_URL, request_url);
curl_easy_setopt(handler, CURLOPT_HTTPGET, 1L);
curl_easy_setopt(handler, CURLOPT_WRITEFUNCTION, curl_write_response);
curl_easy_setopt(handler, CURLOPT_WRITEDATA, buf);
result = curl_easy_perform(handler);
curl_easy_cleanup(handler);
return result;
}

15
src/include/curl.h Normal file
View File

@ -0,0 +1,15 @@
#include <curl/curl.h>
#ifndef CURL_H
#define CURL_H
typedef struct {
char* buf;
size_t len;
} get_response;
void free_get_response(get_response* buf);
CURLcode book_api_call(const char* isbn, get_response* buf);
#endif

16
src/main.c Normal file
View File

@ -0,0 +1,16 @@
#include <stdio.h>
#include "include/curl.h"
int main(void)
{
get_response resp;
book_api_call("9780762437818", &resp);
puts(resp.buf);
free_get_response(&resp);
return 0;
}