mp-utils/src/cat.c

116 lines
1.9 KiB
C
Raw Normal View History

2022-10-01 19:05:39 -04:00
/* cat.c -- program to concatenate named files and/or stdin onto stdout */
/* version 2 */
#include <stdlib.h>
#include <stdio.h>
2022-10-01 19:05:39 -04:00
#include <unistd.h>
#include <string.h>
#include "support.h"
2022-10-01 19:05:39 -04:00
/* parameters */
enum
{
U
};
/* concat - return a buffer of size new_size containing s1 and s2 concatenated. */
char *concat(char *a1, char *a2, int a1_size, int a2_size)
{
2022-10-01 19:05:39 -04:00
char *newbuf;
2022-10-01 19:05:39 -04:00
newbuf = 0;
if( !(newbuf = malloc(a1_size+a2_size)))
{
2022-10-01 19:05:39 -04:00
throw(MALLOC_FAIL, "concat: couldn't create buffer");
}
2022-10-01 19:05:39 -04:00
if(a1_size)
{
mid_mempcpy(newbuf, a1, a1_size, 0);
}
2022-10-01 19:05:39 -04:00
if(a2_size)
{
2022-10-01 19:05:39 -04:00
mid_mempcpy(newbuf, a2, a2_size, a1_size);
}
2022-10-01 19:05:39 -04:00
2022-10-01 19:05:39 -04:00
return(newbuf);
}
2022-10-01 19:05:39 -04:00
int main(int argc, char **argv)
{
2022-10-01 19:05:39 -04:00
int i, c, bufsize, newbufsize;
2022-10-01 19:05:39 -04:00
char *buf, *newbuf;
char pars[1] = {0};
FILE *fd;
i = c = bufsize = newbufsize = 0;
buf = newbuf = 0;
fd = 0;
/* process our parameters */
for(; (c = getopt(argc, argv, "u")) != -1; c = 0)
{
2022-10-01 19:05:39 -04:00
switch(c)
{
2022-10-01 19:05:39 -04:00
case 'u': pars[U] = 1;
break;
case ':':
case '?':
default: throw(NEEDARG_FAIL, mastrcat(argv[0], " [-u] [file ...]"));
break;
}
2022-10-01 19:05:39 -04:00
}
i = optind;
/* i < argc is obvious; steps through all provided args. */
2022-10-02 13:27:00 -04:00
/* !argc-optind && !c is a little less so - it allows this loop to run once if the user provides no paths */
do
2022-10-01 19:05:39 -04:00
{
if( !(fd = file_open(argv[i], "r")))
{
2022-10-01 19:05:39 -04:00
throw(FOPEN_FAIL, mastrcat(argv[0], mastrcat(": could not open file ", argv[i])));
}
2022-10-02 13:27:00 -04:00
2022-10-01 19:05:39 -04:00
if(pars[U])
{
2022-10-02 13:27:00 -04:00
for(; (c = fgetc(fd)) != EOF; c = 0)
{
fputc(c, stdout);
}
}
else
{
newbuf = file_read(fd, &newbufsize);
buf = concat(buf, newbuf, bufsize, newbufsize);
bufsize += newbufsize;
2022-10-01 19:05:39 -04:00
free(newbuf);
}
2022-10-02 13:27:00 -04:00
i++, newbufsize = 0;
}
2022-10-02 13:27:00 -04:00
while((i < argc) || (((argc - optind) == 0) && !c));
2022-10-01 19:05:39 -04:00
if(!pars[U])
{
2022-10-01 19:05:39 -04:00
fwrite(buf, sizeof(char), bufsize, stdout);
}
exit(0);
}