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
115
116
117
118
119
120
121
122
|
/*
* copy input file to backup file. If in_name is /blah/blah/blah/file, then
* backup file will be "file.BAK". Then make the backup file the input and
* original input file the output.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef __TURBOC__
#include <io.h>
#include <alloc.h>
#else
#include <errno.h>
extern *sys_errlist[];
#endif
extern char *ProgName;
#define WARN(msg,param) {\
(void) fprintf(stderr, \
"%s: Error %s \"%s\" - %s\n",\
ProgName,msg,param,sys_errlist[errno]\
);\
++nerrs;\
}
#define FATAL(msg,param) {\
WARN(msg,param);\
if (BackFileName != (char *)0) {\
if (unlink(BackFileName) != 0) \
WARN("removing",BackFileName);\
(void) free(BackFileName);\
}\
return nerrs;\
}
int ProcessFile(InputFileName,ProcessFunc)
char *InputFileName;
int (*ProcessFunc)();
{
char *BackFileName = (char *)0;
int nerrs = 0;
FILE *fin;
FILE *fout;
if ((fin = fopen(InputFileName,"r")) == (FILE *)0)
FATAL("opening",InputFileName);
{
static char BAK[] = ".BAK";
int len = strlen(InputFileName) + sizeof(BAK);
if ((BackFileName = malloc(len)) == (char *)0) {
(void) fprintf(stderr,
"%s: Cannot malloc %d bytes for %s%s\n",
ProgName,len,InputFileName,BAK
);
return ++nerrs;
}
(void) sprintf(BackFileName,"%s%s",InputFileName,BAK);
assert(1 + strlen(BackFileName) == len);
}
/*
** copy InputFileName to backup file
*/
{
int bakchn;
if ((bakchn = creat(BackFileName, 0600)) < 0)
FATAL("create",BackFileName);
{
int n;
char buff[BUFSIZ];
while ((n = read(fileno(fin), buff, sizeof buff)) > 0)
if (write(bakchn, buff, n) != n)
FATAL("writing to",BackFileName);
if (n < 0)
FATAL("reading from",InputFileName);
if (close(bakchn) != 0)
WARN("closing",BackFileName);
if (fclose(fin) != 0)
WARN("closing",InputFileName);
}
}
/*
** re-open backup file as the input file
*/
if ((fin = fopen(BackFileName, "r")) == (FILE *)0)
FATAL("re-opening",BackFileName);
/*
** now the original input file will be the output
*/
if ((fout = fopen(InputFileName, "w")) == (FILE *)0)
FATAL("re-opening",InputFileName);
if (ProcessFunc(fin,fout) != 0) {
(void) fprintf(stderr,
"%s: Could not process file \"%s\"\n",
ProgName,InputFileName
);
if (rename(BackFileName,InputFileName) == 0) {
(void) fprintf(stderr,
"%s: Cannot recover original contents of \"%s\"\n\
Original contents should be in \"%s\"\n",
ProgName,InputFileName,BackFileName
);
nerrs++;
}
} else {
if (fclose(fin) != 0)
WARN("closing",BackFileName);
if (fclose(fout) != 0)
WARN("closing",InputFileName);
}
free(BackFileName);
return nerrs;
}
|