forked from brunonymous/vpopmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seek.c
98 lines (87 loc) · 1.99 KB
/
seek.c
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
/*
* Copyright (C) 2009 Inter7 Internet Technologies, Inc.
*
* Copyright (c) 1987 University of Maryland Computer Science Department.
* All rights reserved.
* Permission to copy for any purpose is hereby granted so long as this
* copyright notice remains intact.
*
* Changed MakeSeekable to use tmpfile() - [email protected]
*/
/*
* Seekable is a predicate which returns true iff a Unix fd is seekable.
*
* MakeSeekable forces an input stdio file to be seekable, by copying to
* a temporary file if necessary.
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
/* commented out for bsd users */
/* long lseek(); */
char *getenv();
int
Seekable(fd)
int fd;
{
return (lseek(fd, 0L, 1) >= 0 && !isatty(fd));
}
int
MakeSeekable(f)
register FILE *f;
{
register int tf, n;
FILE *tmpf;
int blksize;
#ifdef MAXBSIZE
char buf[MAXBSIZE];
struct stat st;
#else
char buf[BUFSIZ];
#endif
if (Seekable(fileno(f)))
return (0);
tmpf = tmpfile(); /* tmpfile() is not safe on all systems */
if (tmpf == NULL) return -1; /* Failed to create temp file */
tf = fileno(tmpf);
/* copy from input file to temp file */
#ifdef MAXBSIZE
if (fstat(tf, &st)) /* how can this ever fail? */
blksize = MAXBSIZE;
else
blksize = vmin(MAXBSIZE, st.st_blksize);
#else
blksize = BUFSIZ;
#endif
while ((n = fread(buf, 1, blksize, f)) > 0) {
if (write(tf, buf, n) != n) {
(void) close(tf);
return (-1);
}
}
/* ferror() is broken in Ultrix 1.2; hence the && */
if (ferror(f) && !feof(f)) {
(void) close(tf);
return (-1);
}
/*
* Now switch f to point at the temp file. Since we hit EOF, there
* is nothing in f's stdio buffers, so we can play a dirty trick:
*/
clearerr(f);
if (dup2(tf, fileno(f))) {
(void) close(tf);
return (-1);
}
(void) close(tf);
return (0);
}
/* suggested by Ken Jones instead of MIN for better compatibility */
int vmin( int x, int y)
{
if ( x > y ) return(x);
return(y);
}