me-utils/src/overwrite.c

62 lines
1.2 KiB
C

/* Overwrite.c -- program to exhaust stdin, then write it to a file */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "support.h"
int main(int argc, char **argv)
{
int buflen, strlen;
int c;
char *buf;
FILE *fp;
strlen = 0;
/* arbitrary */
buflen = 4096;
if(argc == 1)
{
throw(NEEDARG_FAIL, mastrcat(argv[0], " files"));
}
if((buf = malloc(buflen)))
{
c = 0;
for(;((c = getchar()) != EOF);)
{
if(strlen == buflen && !(buf = realloc(buf, (buflen*=2))))
{
/* realloc failed */
throw(MALLOC_FAIL, NULL);
}
buf[strlen++] = c;
}
if(!(fp = fopen(argv[1], "a")))
{
throw(FOPEN_FAIL, argv[1]);
}
for(c = 0; c <= strlen; c++)
{
if(fputc(buf[c], fp) == EOF)
{
throw(WRITE_FAIL, argv[1]);
}
}
/* close the file and exit successfully */
fclose(fp);
}
else
{
throw(MALLOC_FAIL, NULL);
}
return 0;
}