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