Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created December 10, 2014 07:00
Show Gist options
  • Save 1995eaton/5caa44dfc072758825a7 to your computer and use it in GitHub Desktop.
Save 1995eaton/5caa44dfc072758825a7 to your computer and use it in GitHub Desktop.
My own implementation of the Unix sponge command: http://linux.die.net/man/1/sponge
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char *text;
size_t len;
} filedata_t;
filedata_t *
read_stdin (void)
{
filedata_t *result = malloc (sizeof (filedata_t));
result->len = 0;
size_t cap = 4096;
result->text = malloc (cap * sizeof (char));
for (;;)
{
int c = fgetc (stdin);
if (feof (stdin))
break;
result->text[result->len] = (char) c;
if (++result->len == cap)
result->text = realloc (result->text, (cap *= 2) * sizeof (char));
}
result->text = realloc (result->text, (result->len + 1) * sizeof (char));
result->text[result->len] = '\0';
return result;
}
void
write_file (const char *file_name, const filedata_t * fdata)
{
FILE *fp = fopen (file_name, "wb");
fwrite (fdata->text, fdata->len * sizeof (char), 1, fp);
fclose (fp);
}
int
main (int argc, char **argv)
{
filedata_t *fdata = read_stdin ();
if (argc == 2)
{
write_file (argv[1], fdata);
}
else
{
printf ("%s", fdata->text);
}
free (fdata->text);
free (fdata);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment