1
0
Fork 0
mirror of https://github.com/tailix/libkernaux.git synced 2024-10-30 11:54:01 -04:00
libkernaux/examples/fprintf_va.c

39 lines
913 B
C
Raw Normal View History

2022-06-14 08:03:17 -04:00
#include <kernaux/io.h>
2020-12-06 19:27:42 -05:00
#include <kernaux/printf.h>
#include <assert.h>
2022-01-19 07:01:21 -05:00
#include <stddef.h>
2020-12-06 19:27:42 -05:00
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
2022-01-20 06:58:08 -05:00
static const char *const data = "foobar";
2020-12-06 19:27:42 -05:00
static char buffer[BUFFER_SIZE];
2021-12-16 10:26:16 -05:00
static size_t buffer_index = 0;
2020-12-06 19:27:42 -05:00
2022-01-20 06:58:08 -05:00
static void my_putchar(const char chr, void *arg)
2020-12-06 19:27:42 -05:00
{
2022-01-20 06:58:08 -05:00
assert(arg == data);
2020-12-06 19:27:42 -05:00
if (buffer_index >= BUFFER_SIZE) abort();
buffer[buffer_index++] = chr;
}
2022-01-20 06:58:08 -05:00
static int my_printf(const char *const format, ...)
2020-12-06 19:27:42 -05:00
{
va_list va;
va_start(va, format);
struct KernAux_File file = KernAux_File_create(my_putchar);
const int result = kernaux_vfprintf(&file, (char*)data, format, va);
2020-12-06 19:27:42 -05:00
va_end(va);
2022-01-20 06:58:08 -05:00
return result;
2020-12-06 19:27:42 -05:00
}
void example_main()
2020-12-06 19:27:42 -05:00
{
2022-01-20 06:58:08 -05:00
const int result = my_printf("Hello, %s! Session ID: %u.", "Alex", 123);
assert((size_t)result == strlen(buffer));
2020-12-06 19:27:42 -05:00
assert(strcmp(buffer, "Hello, Alex! Session ID: 123.") == 0);
}