Files
CS361-Computer-Systems-II/p1-sh/utils/repeat.c
T

77 lines
1.4 KiB
C
Raw Normal View History

2026-05-31 14:34:00 -04:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void usage (void) __attribute__ ((unused));
int
main (int argc, char *argv[], char *envp[])
{
if (argc < 3)
{
usage();
return EXIT_FAILURE;
}
int i = 1;
while (i < argc)
{
char *endptr;
long count = strtol (argv[i], &endptr, 10);
if (*endptr != '\0' || count <= 0)
{
usage();
return EXIT_FAILURE;
}
i++;
if (i >= argc)
{
usage();
return EXIT_FAILURE;
}
char *var = argv[i];
char *val = NULL;
int x = 0;
while (envp[x] != NULL)
{
if (strstr(envp[x], var) == envp[x])
{
val = envp[x];
break;
}
x++;
}
if (val == NULL)
{
val = "";
for (long j = 0; j < count; j++)
{
printf("%s=%s\n", var, val);
}
val = "";
}
else
{
for (long j = 0; j < count; j++)
{
printf("%s\n", val);
}
}
i++;
}
return EXIT_SUCCESS;
}
static void
usage (void)
{
printf ("repeat, a tool for printing repeated environment variables\n");
printf ("usage: repeat N VAR ...\n");
printf ("each N must be a positive integer\n");
printf ("N VAR can be repeated, but each repetition must have both\n");
}