1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License, Version 1.0 only 6 * (the "License"). You may not use this file except in compliance 7 * with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or http://www.opensolaris.org/os/licensing. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */ 23 /* All Rights Reserved */ 24 25 26 /* 27 * Copyright (c) 1985 AT&T 28 * All Rights Reserved 29 */ 30 #ident "%Z%%M% %I% %E% SMI" /* SVr4.0 1.1 */ 31 32 #include <stdio.h> 33 #include <fcntl.h> 34 35 #define LOOKING 1 36 #define SKIPPING 2 37 38 char * 39 chgenv(file, name, val) 40 char *file; 41 char *name; 42 char *val; 43 { 44 char inbuf[BUFSIZ]; 45 char outbuf[BUFSIZ]; 46 register char *p; 47 char *index; 48 register int c; 49 register int state; 50 register FILE *infp; 51 register FILE *outfp; 52 int len; 53 char *strnsave(); 54 char *backslash(); 55 FILE *tempfile(); 56 57 if ((outfp = tempfile(NULL, "w+")) == NULL) 58 return NULL; 59 setbuf(outfp, outbuf); 60 if (val) { 61 fputs(name, outfp); 62 putc('=', outfp); 63 len = 2 * strlen(val); 64 fputs(p = backslash(strnsave(val, len), len), outfp); 65 free(p); 66 putc('\n', outfp); 67 } 68 if ((infp = fopen(file, "r+"))) { 69 setbuf(infp, inbuf); 70 state = LOOKING; 71 index = name; 72 for (c = getc(infp); c != EOF; c = getc(infp)) { 73 if (state == SKIPPING) { 74 if (c == '\n') { 75 state = LOOKING; 76 index = name; 77 } 78 continue; 79 } 80 if (state == LOOKING) { 81 /* if we are in name */ 82 if (*index) { 83 if (c == *index) { 84 index++; 85 continue; 86 } 87 } 88 /* found name, look for "=" */ 89 else if (c == '=') { 90 state = SKIPPING; 91 continue; 92 } 93 /* failure, copy line to outfile */ 94 for (p = name; p < index; p++) 95 putc(*p, outfp); 96 state = 0; 97 } 98 if (c == '\n') { 99 state = LOOKING; 100 index = name; 101 } 102 putc(c, outfp); 103 } 104 fclose(infp); 105 } 106 { 107 register int fd; 108 register int n; 109 110 if ((fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0640)) >= 0) { 111 fseek(outfp, 0L, 0); 112 while ((n = fread(inbuf, 1, sizeof(inbuf), outfp)) > 0) 113 write(fd, inbuf, n); 114 close(fd); 115 } 116 else 117 val = NULL; 118 } 119 fclose(outfp); 120 return val; 121 } 122