Skip to content

Commit 2e7cbd1

Browse files
committed
small input downloader
1 parent aa61631 commit 2e7cbd1

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
inputs/
22
.vscode/
33
.DS_Store
4+
get_input

get_input.c

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <curl/curl.h>
4+
5+
// Replace with your session cookie value
6+
#define BASE_URL "https://adventofcode.com/2024/day/%d/input"
7+
8+
// Callback function to write data to a file
9+
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
10+
size_t written = fwrite(ptr, size, nmemb, stream);
11+
return written;
12+
}
13+
14+
int main(int argc, char *argv[]) {
15+
if (argc != 3) {
16+
fprintf(stderr, "Usage: %s <session_cookie> <day>\n", argv[0]);
17+
return 1;
18+
}
19+
20+
// Parse command line arguments
21+
int day = atoi(argv[2]);
22+
if (day < 1 || day > 25) {
23+
fprintf(stderr, "Invalid day\n");
24+
return 1;
25+
}
26+
27+
char *session_cookie = argv[1];
28+
29+
CURL *curl;
30+
CURLcode res;
31+
32+
// Prepare the URL
33+
char url[256];
34+
snprintf(url, sizeof(url), BASE_URL, day);
35+
36+
// Prepare the file path
37+
char file_path[256];
38+
snprintf(file_path, sizeof(file_path), "inputs/day%d", day);
39+
40+
// Create the "inputs" directory if it doesn't exist
41+
if (system("mkdir -p inputs") != 0) {
42+
perror("Error creating directory");
43+
return 1;
44+
}
45+
46+
FILE *fp = fopen(file_path, "wb");
47+
if (!fp) {
48+
perror("Error opening file");
49+
return 1;
50+
}
51+
52+
// Initialize CURL
53+
curl = curl_easy_init();
54+
if (curl) {
55+
// Set URL
56+
curl_easy_setopt(curl, CURLOPT_URL, url);
57+
58+
// Set the session cookie in the header
59+
struct curl_slist *headers = NULL;
60+
char cookie_header[512];
61+
snprintf(cookie_header, sizeof(cookie_header), "Cookie: session=%s", session_cookie);
62+
headers = curl_slist_append(headers, cookie_header);
63+
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
64+
65+
// Set the User-Agent (optional but recommended)
66+
curl_easy_setopt(curl, CURLOPT_USERAGENT, "C program for Advent of Code input");
67+
68+
// Write data to the file
69+
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
70+
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
71+
72+
// Perform the request
73+
res = curl_easy_perform(curl);
74+
if (res != CURLE_OK) {
75+
fprintf(stderr, "CURL error: %s\n", curl_easy_strerror(res));
76+
} else {
77+
printf("Input for day %d successfully saved to %s\n", day, file_path);
78+
}
79+
80+
// Clean up
81+
curl_easy_cleanup(curl);
82+
curl_slist_free_all(headers);
83+
} else {
84+
fprintf(stderr, "Error initializing CURL\n");
85+
}
86+
87+
fclose(fp);
88+
return 0;
89+
}

0 commit comments

Comments
 (0)