releasing version 0.5
[moreutils.git] / sponge.c
blob59952ea84060e66023e4fc0c8cdd5db76f8cd09d
1 /*
2 * sponge.c - read in all available info from stdin, then output it to
3 * file named on the command line
5 * Copyright © 2006 Tollef Fog Heen
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * version 2 as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 * USA
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <string.h>
32 void usage() {
33 printf("sponge <file>: suck in all input from stdin and write it to <file>");
34 exit(0);
37 int main(int argc, char **argv) {
38 char *buf, *bufstart;
39 size_t bufsize = 8192;
40 size_t bufused = 0;
41 ssize_t i = 0;
42 int outfd;
44 if (argc != 2) {
45 usage();
48 bufstart = buf = malloc(bufsize);
49 if (!buf) {
50 perror("malloc");
51 exit(1);
54 while ((i = read(0, buf, bufsize - bufused)) > 0) {
55 bufused = bufused+i;
56 if (bufused == bufsize) {
57 bufsize *= 2;
58 bufstart = realloc(bufstart, bufsize);
59 if (!bufstart) {
60 perror("realloc");
61 exit(1);
64 buf = bufstart + bufused;
67 if (i == -1) {
68 perror("read");
69 exit(1);
72 outfd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
73 if (outfd == -1) {
74 fprintf(stderr, "Can't open %s: %s\n", argv[1], strerror(errno));
75 exit(1);
78 i = write(outfd, bufstart, bufused);
79 if (i == -1) {
80 perror("write");
81 exit(1);
84 i = close(outfd);
85 if (i == -1) {
86 perror("close");
87 exit(1);
90 return 0;