libkernaux/examples/printf_file_va.c

37 lines
836 B
C
Raw Permalink Normal View History

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