Modify README. Remove redundant assignment from overwrite.c.

Add additional error handling to overwrite.c.
This commit is contained in:
Mid Favila 2022-09-13 18:12:37 -04:00
parent cd3f05e0b8
commit 9d80a006d5
2 changed files with 33 additions and 32 deletions

3
README
View File

@ -12,5 +12,6 @@
with fewer than the provided number of characters with the next with fewer than the provided number of characters with the next
line, so long as it doesn't cause a word-split. line, so long as it doesn't cause a word-split.
-overwrite: Reads stdin and writes it to the provided file. [done] -overwrite: Reads stdin and writes it to the provided file. [done]
-shuf: Accepts an arbitrary number of arguments; returns one at random. -shuf: Accepts an arbitrary number of arguments; returns one at random.
-rand: Shell interface to the C rand() function.

View File

@ -14,48 +14,48 @@ int main(int argc, char **argv)
char *buf; char *buf;
FILE *fp; FILE *fp;
strlen = 0; strlen = 0;
buflen = 0;
/* arbitrary */ /* arbitrary */
buflen = 4096; buflen = 4096;
if(argc == 1) if(argc == 1)
{ {
throw(NEEDARG_FAIL, mastrcat(argv[0], " files")); throw(NEEDARG_FAIL, mastrcat(argv[0], " files"));
} }
if((buf = malloc(buflen))) if((buf = malloc(buflen)))
{ {
c = 0; c = 0;
for(;((c = getchar()) != EOF);) for(;((c = getchar()) != EOF);)
{ {
if(strlen == buflen) if(strlen == buflen && !(buf = realloc(buf, (buflen*=2))))
{ {
buf = realloc(buf, (buflen*=2)); /* realloc failed */
throw(MALLOC_FAIL, NULL);
} }
buf[strlen++] = c; buf[strlen++] = c;
} }
if(!(fp = fopen(argv[1], "a"))) if(!(fp = fopen(argv[1], "a")))
{ {
throw(FOPEN_FAIL, argv[1]); throw(FOPEN_FAIL, argv[1]);
} }
for(c = 0; c <= strlen; c++) for(c = 0; c <= strlen; c++)
{ {
if(fputc(buf[c], fp) == EOF) if(fputc(buf[c], fp) == EOF)
{ {
throw(WRITE_FAIL, argv[1]); throw(WRITE_FAIL, argv[1]);
} }
} }
/* close the file and exit successfully */ /* close the file and exit successfully */
fclose(fp); fclose(fp);
} }
else else
{ {
throw(MALLOC_FAIL, NULL); throw(MALLOC_FAIL, NULL);
} }
return 0; return 0;
} }