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