summaryrefslogtreecommitdiffstats
path: root/usr.sbin/ctm/ctm/ctm_ed.c
blob: 80425054b6902c213f7044bfd314256567759158 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <phk@login.dknet.dk> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
 * ----------------------------------------------------------------------------
 *
 * $FreeBSD$
 *
 */

#include "ctm.h"

int
ctm_edit(u_char *script, int length, char *filein, char *fileout)
{
    u_char *ep, cmd;
    int ln, ln2, iln, ret=0, c;
    FILE *fi=0,*fo=0;

    fi = fopen(filein,"r");
    if(!fi) {
	perror(filein);
	return 8;
    }

    fo = fopen(fileout,"w");
    if(!fo) {
	perror(fileout);
	fclose(fi);
	return 4;
    }
    iln = 1;
    for(ep=script;ep < script+length;) {
	cmd = *ep++;
	if(cmd != 'a' && cmd != 'd') { ret = 1; goto bye; }
	ln = 0;
	while(isdigit(*ep)) {
	    ln *= 10;
	    ln += (*ep++ - '0');
	}
	if(*ep++ != ' ') { ret = 1; goto bye; }
	ln2 = 0;
	while(isdigit(*ep)) {
	    ln2 *= 10;
	    ln2 += (*ep++ - '0');
	}
	if(*ep++ != '\n') { ret = 1; goto bye; }


	if(cmd == 'd') {
	    while(iln < ln) {
		c = getc(fi);
		if(c == EOF) { ret = 1; goto bye; }
		putc(c,fo);
		if(c == '\n')
		    iln++;
	    }
	    while(ln2) {
		c = getc(fi);
		if(c == EOF) { ret = 1; goto bye; }
		if(c != '\n')
		    continue;
		ln2--;
		iln++;
	    }
	    continue;
	}
	if(cmd == 'a') {
	    while(iln <= ln) {
		c = getc(fi);
		if(c == EOF) { ret = 1; goto bye; }
		putc(c,fo);
		if(c == '\n')
		    iln++;
	    }
	    while(ln2) {
		c = *ep++;
		putc(c,fo);
		if(c != '\n')
		    continue;
		ln2--;
	    }
	    continue;
	}
	ret = 1;
	goto bye;
    }
    while(1) {
	c = getc(fi);
	if(c == EOF) break;
	putc(c,fo);
    }
    ret = 0;
bye:
    if(fi) {
	if(fclose(fi) != 0) {
	    perror(filein);
	    ret = 1;
	}
    }
    if(fo) {
     	if(fflush(fo) != 0) {
	    perror(fileout);
	    ret = 1;
     	}
     	if(fclose(fo) != 0) {
	    perror(fileout);
	    ret = 1;
     	}
    }
    return ret;
}
OpenPOWER on IntegriCloud