Swap code/variable declaration to be pre-C99 compliant.
[xiph/unicode.git] / cdparanoia / buffering_write.c
blob9dec7bcd11d561e64724dbf0dad577f87bde8e20
1 /* Eliminate teeny little writes. patch submitted by
2 Rob Ross <rbross@parl.ces.clemson.edu> --Monty 19991008 */
4 #include <string.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <stdio.h>
9 #define OUTBUFSZ 32*1024
11 #include "utils.h"
12 extern long blocking_write(int outf, char *buffer, long num);
15 /* GLOBALS FOR BUFFERING CALLS */
16 static int bw_fd = -1;
17 static long bw_pos = 0;
18 static char bw_outbuf[OUTBUFSZ];
21 /* buffering_write() - buffers data to a specified size before writing.
23 * Restrictions:
24 * - MUST CALL BUFFERING_CLOSE() WHEN FINISHED!!!
27 long buffering_write(int fd, char *buffer, long num)
29 if (fd != bw_fd) {
30 /* clean up after buffering for some other file */
31 if (bw_fd >= 0 && bw_pos > 0) {
32 if (blocking_write(bw_fd, bw_outbuf, bw_pos)) {
33 perror("write (in buffering_write, flushing)");
36 bw_fd = fd;
37 bw_pos = 0;
40 if (bw_pos + num > OUTBUFSZ) {
41 /* fill our buffer first, then write, then modify buffer and num */
42 memcpy(&bw_outbuf[bw_pos], buffer, OUTBUFSZ - bw_pos);
43 if (blocking_write(fd, bw_outbuf, OUTBUFSZ)) {
44 perror("write (in buffering_write, full buffer)");
45 return(-1);
47 num -= (OUTBUFSZ - bw_pos);
48 buffer += (OUTBUFSZ - bw_pos);
49 bw_pos = 0;
51 /* save data */
52 memcpy(&bw_outbuf[bw_pos], buffer, num);
53 bw_pos += num;
55 return(0);
58 /* buffering_close() - writes out remaining buffered data before closing
59 * file.
62 int buffering_close(int fd)
64 if (fd == bw_fd && bw_pos > 0) {
65 /* write out remaining data and clean up */
66 if (blocking_write(fd, bw_outbuf, bw_pos)) {
67 perror("write (in buffering_close)");
69 bw_fd = -1;
70 bw_pos = 0;
72 return(close(fd));