releasing version 0.28
[moreutils.git] / sponge.c
bloba7914eadccc88d4a3cb0b08cf2245337aac58036
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>\n");
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 || (argc == 2 && strcmp(argv[1], "-h") == 0)) {
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;
66 if (i == -1) {
67 perror("read");
68 exit(1);
71 if (argc == 2) {
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 else {
79 outfd = 1;
82 i = write(outfd, bufstart, bufused);
83 if (i == -1) {
84 perror("write");
85 exit(1);
88 i = close(outfd);
89 if (i == -1) {
90 perror("close");
91 exit(1);
94 return 0;