xref: /netbsd-src/external/bsd/nvi/dist/ex/ex_mkexrc.c (revision 75219f3a016dfaad1cb304eb017f9787b1de8292)
1 /*	$NetBSD: ex_mkexrc.c,v 1.2 2013/11/22 15:52:05 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 #ifndef lint
14 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 ";
15 #endif /* not lint */
16 
17 #include <sys/types.h>
18 #include <sys/queue.h>
19 #include <sys/stat.h>
20 
21 #include <bitstring.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 
30 #include "../common/common.h"
31 #include "pathnames.h"
32 
33 /*
34  * ex_mkexrc -- :mkexrc[!] [file]
35  *
36  * Create (or overwrite) a .exrc file with the current info.
37  *
38  * PUBLIC: int ex_mkexrc __P((SCR *, EXCMD *));
39  */
40 int
41 ex_mkexrc(SCR *sp, EXCMD *cmdp)
42 {
43 	struct stat sb;
44 	FILE *fp;
45 	int fd, sverrno;
46 	const char *fname;
47 	size_t flen;
48 
49 	switch (cmdp->argc) {
50 	case 0:
51 		fname = _PATH_EXRC;
52 		INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1,
53 			    fname, flen);
54 		set_alt_name(sp, fname);
55 		break;
56 	default:
57 		abort();
58 	}
59 
60 	if (!FL_ISSET(cmdp->iflags, E_C_FORCE) && !stat(fname, &sb)) {
61 		msgq_str(sp, M_ERR, fname,
62 		    "137|%s exists, not written; use ! to override");
63 		return (1);
64 	}
65 
66 	/* Create with max permissions of rw-r--r--. */
67 	if ((fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY,
68 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
69 		msgq_str(sp, M_SYSERR, fname, "%s");
70 		return (1);
71 	}
72 
73 	if ((fp = fdopen(fd, "w")) == NULL) {
74 		sverrno = errno;
75 		(void)close(fd);
76 		goto e2;
77 	}
78 
79 	if (seq_save(sp, fp, "abbreviate ", SEQ_ABBREV) || ferror(fp))
80 		goto e1;
81 	if (seq_save(sp, fp, "map ", SEQ_COMMAND) || ferror(fp))
82 		goto e1;
83 	if (seq_save(sp, fp, "map! ", SEQ_INPUT) || ferror(fp))
84 		goto e1;
85 	if (opts_save(sp, fp) || ferror(fp))
86 		goto e1;
87 	if (fclose(fp)) {
88 		sverrno = errno;
89 		goto e2;
90 	}
91 
92 	msgq_str(sp, M_INFO, fname, "138|New exrc file: %s");
93 	return (0);
94 
95 e1:	sverrno = errno;
96 	(void)fclose(fp);
97 e2:	errno = sverrno;
98 	msgq_str(sp, M_SYSERR, fname, "%s");
99 	return (1);
100 }
101