Imported Upstream version 0.4.8
[platform/upstream/libsmi.git] / tools / fprint.c
1 /*
2  * fprint.c --
3  *
4  *      This file defines commonly used utility functions to produce
5  *      nicely indented output.
6  *
7  * Copyright (c) 1999 Frank Strauss, Technical University of Braunschweig.
8  * Copyright (c) 2007 J. Schoenwaelder, Jacobs University Bremen.
9  *
10  * See the file "COPYING" for information on usage and redistribution
11  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
12  *
13  * @(#) $Id: fprint.c 8024 2008-04-11 13:25:26Z schoenw $
14  */
15
16
17
18 #include <config.h>
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdarg.h>
24 #ifdef HAVE_WIN_H
25 #include "win.h"
26 #endif
27
28 #include "smi.h"
29 #include "fprint.h"
30
31 /*
32  * This module keeps internal state. Hence, these functions are not
33  * thread safe. Note, however, that multi-threaded concurrent output
34  * generation may not be such a wonderful idea anyway - so using
35  * static variables may be good enough.
36  */
37
38
39 int fprint_current_column = 0;
40 int fprint_indent_max = 64;
41 int fprint_indent_texts = 4;
42
43
44
45 void
46 fprint(FILE *f, char *fmt, ...)
47 {
48     va_list ap;
49     char    *s;
50     char    *p;
51     
52     va_start(ap, fmt);
53     fprint_current_column += smiVasprintf(&s, fmt, ap);
54     va_end(ap);
55     fputs(s, f);
56     if ((p = strrchr(s, '\n'))) {
57         fprint_current_column = strlen(p) - 1;
58     }
59     free(s);
60 }
61
62
63
64 void
65 fprintSegment(FILE *f, int column, char *string, int length)
66 {
67     fprint(f, "%*c%s", column, ' ', string);
68     if (length) {
69         fprint(f, "%*c", length - strlen(string) - column, ' ');
70     }
71 }
72
73
74
75 void
76 fprintWrapped(FILE *f, int column, char *string)
77 {
78     if ((fprint_current_column + strlen(string)) > fprint_indent_max) {
79         putc('\n', f);
80         fprint_current_column = 0;
81         fprintSegment(f, column, "", 0);
82     }
83     fprint(f, "%s", string);
84 }
85
86
87
88 void
89 fprintMultilineString(FILE *f, int column, const char *s)
90 {
91     int i, len;
92     
93     fprintSegment(f, column - 1 + fprint_indent_texts, "\"", 0);
94     if (s) {
95         len = strlen(s);
96         for (i=0; i < len; i++) {
97             putc(s[i], f);
98             fprint_current_column++;
99             if (s[i] == '\n') {
100                 fprint_current_column = 0;
101                 fprintSegment(f, column + fprint_indent_texts, "", 0);
102             }
103         }
104     }
105     putc('\"', f);
106     fprint_current_column++;
107 }