soft-exp/ex03/mixed/mixed02.c
2025-05-22 10:44:24 +02:00

73 lines
1.8 KiB
C
Executable File

#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 128
typedef struct creds creds_t;
typedef struct creds {
char str[BUF_SIZE];
void (*welcome)(void);
} creds_t;
static creds_t *creds;
/* internal prototypes */
static void cat(const char *s1, uint32_t len1, const char *s2, uint32_t len2);
static void print(void);
static void s3cr3t(void);
/* entry point */
// ./mixed02 dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd 4294967295 d 10
int main(int argc, char **argv) {
if (argc < 5) {
printf("usage: %s <string1> <length1> <string2> <length2>\n", argv[0]);
return -1;
}
char *endptr;
errno = 0;
uint32_t len1 = (uint32_t)strtoul(argv[2], &endptr, 10);
if (errno || *endptr) {
fprintf(stderr, "Conversion error, non-convertible part: %s\n", endptr);
exit(EXIT_FAILURE);
}
errno = 0;
uint32_t len2 = (uint32_t)strtoul(argv[4], &endptr, 10);
if (errno || *endptr) {
fprintf(stderr, "Conversion error, non-convertible part: %s\n", endptr);
exit(EXIT_FAILURE);
}
creds = (creds_t *)calloc(1, sizeof(creds_t));
if (!creds) {
perror("calloc");
return -1;
}
creds->welcome = print;
cat(argv[1], len1, argv[3], len2);
creds->welcome();
free(creds);
return 0;
}
/* internal function definitions */
static void cat(const char *s1, uint32_t len1, const char *s2, uint32_t len2) {
if ((len1 + len2) >= BUF_SIZE) {
fprintf(stderr, "Input strings exceed buffer size\n");
exit(EXIT_FAILURE);
}
snprintf(creds->str, len1 + 1, "%s", s1);
// TODO: creds->str+len1+1
snprintf(creds->str + len1, len2 + 1, "%s", s2);
}
static void print(void) { printf("%s!\n", creds->str); }
static void s3cr3t(void) { printf("You've gathered secret material!\n"); }