File: wrap_printf.c

package info (click to toggle)
drbd-utils 9.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,388 kB
  • sloc: ansic: 43,698; xml: 15,968; cpp: 7,783; sh: 3,699; makefile: 1,353; perl: 353
file content (76 lines) | stat: -rw-r--r-- 1,228 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>

__attribute__((format(printf, 2, 3)))
int wrap_printf(int indent, const char *format, ...)
{
	static int columns, col;
	va_list ap1, ap2;
	int n;
	const char *nl;

	if (columns == 0) {
		struct winsize ws = { };

		ioctl(1, TIOCGWINSZ, &ws);
		columns = ws.ws_col;
		if (columns <= 0)
			columns = 80;
	}

	va_start(ap1, format);
	va_copy(ap2, ap1);
	n = vsnprintf(NULL, 0, format, ap1);
	va_end(ap1);
	if (col + n > columns) {
		putchar('\n');
		if (*format == '\n')
			format++;
		col = 0;
	}
	if (col == 0) {
		while (*format == ' ')
			format++;
		col += indent;
		while (indent--)
			putchar(' ');
	}
	n = vprintf(format, ap2);
	va_end(ap2);
	if (n > 0)
		col += n;

	nl = strrchr(format, '\n');
	if (nl && nl[1] == 0)
		col = 0;

	return n;
}

int wrap_printf_wordwise(int indent, const char *str)
{
	int n = 0;

	do {
		const char *fmt = "%.*s", *s;
		int m;

		if (*str == ' ') {
			fmt = " %.*s";
			while (*str == ' ')
				str++;
		}
		for (s = str; *s && *s != ' '; s++)
			/* nothing */ ;
		m = wrap_printf(indent, fmt, s - str, str);
		if (m < 0)
			return m;
		n += m;
		str = s;
	} while (*str);

	return n;
}