]> diplodocus.org Git - nmh/blob - sbr/fmt_new.c
Improve fmttest output
[nmh] / sbr / fmt_new.c
1 /* fmt_new.c -- read format file/string and normalize
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include "h/mh.h"
9 #include "fmt_new.h"
10 #include "getcpy.h"
11 #include "error.h"
12 #include "h/utils.h"
13
14 #define QUOTE '\\'
15
16 static char *formats = 0;
17
18 /*
19 * static prototypes
20 */
21 static void normalize (char *);
22
23
24 /*
25 * Get new format string
26 */
27
28 char *
29 new_fs (char *form, char *format, char *default_fs)
30 {
31 struct stat st;
32 FILE *fp;
33
34 free(formats);
35
36 if (form) {
37 if ((fp = fopen (etcpath (form), "r")) == NULL)
38 adios (form, "unable to open format file");
39
40 if (fstat (fileno (fp), &st) == -1)
41 adios (form, "unable to stat format file");
42
43 formats = mh_xmalloc ((size_t) st.st_size + 1);
44
45 if (read (fileno(fp), formats, (int) st.st_size) != st.st_size)
46 adios (form, "error reading format file");
47
48 formats[st.st_size] = '\0';
49
50 fclose (fp);
51 } else {
52 formats = getcpy (format ? format : default_fs);
53 }
54
55 normalize (formats); /* expand escapes */
56
57 return formats;
58 }
59
60
61 void
62 free_fs(void)
63 {
64 free (formats);
65 formats = 0;
66 }
67
68
69 /*
70 * Expand escapes in format strings
71 */
72
73 static void
74 normalize (char *cp)
75 {
76 char *dp;
77
78 for (dp = cp; *cp; cp++) {
79 if (*cp != QUOTE) {
80 *dp++ = *cp;
81 } else {
82 switch (*++cp) {
83 case 'b':
84 *dp++ = '\b';
85 break;
86
87 case 'f':
88 *dp++ = '\f';
89 break;
90
91 case 'n':
92 *dp++ = '\n';
93 break;
94
95 case 'r':
96 *dp++ = '\r';
97 break;
98
99 case 't':
100 *dp++ = '\t';
101 break;
102
103 case '\n':
104 break;
105
106 case 0:
107 cp--;
108 /* FALLTHRU */
109 default:
110 *dp++ = *cp;
111 break;
112 }
113 }
114 }
115 *dp = '\0';
116 }