Merge from vendor branch DIFFUTILS:
[dragonfly.git] / contrib / nvi / ex / ex_mkexrc.c
1 /*-
2  * Copyright (c) 1992, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1992, 1993, 1994, 1995, 1996
5  *      Keith Bostic.  All rights reserved.
6  *
7  * See the LICENSE file for redistribution information.
8  */
9
10 #include "config.h"
11
12 #ifndef lint
13 static const char sccsid[] = "@(#)ex_mkexrc.c   10.11 (Berkeley) 3/6/96";
14 #endif /* not lint */
15
16 #include <sys/types.h>
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19
20 #include <bitstring.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28
29 #include "../common/common.h"
30 #include "pathnames.h"
31
32 /*
33  * ex_mkexrc -- :mkexrc[!] [file]
34  *
35  * Create (or overwrite) a .exrc file with the current info.
36  *
37  * PUBLIC: int ex_mkexrc __P((SCR *, EXCMD *));
38  */
39 int
40 ex_mkexrc(sp, cmdp)
41         SCR *sp;
42         EXCMD *cmdp;
43 {
44         struct stat sb;
45         FILE *fp;
46         int fd, sverrno;
47         char *fname;
48
49         switch (cmdp->argc) {
50         case 0:
51                 fname = _PATH_EXRC;
52                 break;
53         case 1:
54                 fname = cmdp->argv[0]->bp;
55                 set_alt_name(sp, fname);
56                 break;
57         default:
58                 abort();
59         }
60
61         if (!FL_ISSET(cmdp->iflags, E_C_FORCE) && !stat(fname, &sb)) {
62                 msgq_str(sp, M_ERR, fname,
63                     "137|%s exists, not written; use ! to override");
64                 return (1);
65         }
66
67         /* Create with max permissions of rw-r--r--. */
68         if ((fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY,
69             S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
70                 msgq_str(sp, M_SYSERR, fname, "%s");
71                 return (1);
72         }
73
74         if ((fp = fdopen(fd, "w")) == NULL) {
75                 sverrno = errno;
76                 (void)close(fd);
77                 goto e2;
78         }
79
80         if (seq_save(sp, fp, "abbreviate ", SEQ_ABBREV) || ferror(fp))
81                 goto e1;
82         if (seq_save(sp, fp, "map ", SEQ_COMMAND) || ferror(fp))
83                 goto e1;
84         if (seq_save(sp, fp, "map! ", SEQ_INPUT) || ferror(fp))
85                 goto e1;
86         if (opts_save(sp, fp) || ferror(fp))
87                 goto e1;
88         if (fclose(fp)) {
89                 sverrno = errno;
90                 goto e2;
91         }
92
93         msgq_str(sp, M_INFO, fname, "138|New exrc file: %s");
94         return (0);
95
96 e1:     sverrno = errno;
97         (void)fclose(fp);
98 e2:     errno = sverrno;
99         msgq_str(sp, M_SYSERR, fname, "%s");
100         return (1);
101 }