Removed submodules
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// You may assume that lines are no longer than 1024 bytes
|
||||
#define LINELEN 1024
|
||||
|
||||
static void usage (void);
|
||||
|
||||
int
|
||||
main (int argc, char *argv[])
|
||||
{
|
||||
int opt;
|
||||
char *delimitter = " ";
|
||||
long field = 1;
|
||||
|
||||
while ((opt = getopt (argc, argv, "d:f:")) != -1)
|
||||
{
|
||||
switch (opt)
|
||||
{
|
||||
case 'd':
|
||||
delimitter = optarg;
|
||||
break;
|
||||
case 'f':
|
||||
field = strtol (optarg, NULL, 10);
|
||||
break;
|
||||
default:
|
||||
printf ("./bin/cut: invalid option -- \'%c\'\n", optopt);
|
||||
exit (EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
if (field < 1)
|
||||
{
|
||||
usage ();
|
||||
exit (EXIT_FAILURE);
|
||||
}
|
||||
|
||||
FILE *file = optind < argc ? fopen (argv[optind], "r") : stdin;
|
||||
if (file == NULL)
|
||||
{
|
||||
perror ("Failed to open input file");
|
||||
exit (EXIT_FAILURE);
|
||||
}
|
||||
|
||||
char buffer[LINELEN];
|
||||
|
||||
while (fgets (buffer, sizeof (buffer), file) != NULL)
|
||||
{
|
||||
buffer[strcspn (buffer, "\n")] = '\0';
|
||||
|
||||
char *token = strtok (buffer, delimitter);
|
||||
long i = 1;
|
||||
while (i++ < field) token = strtok (NULL, delimitter);
|
||||
|
||||
printf("%s\n", token != NULL ? token : "");
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
static void
|
||||
usage (void)
|
||||
{
|
||||
printf ("cut, splits each line based on a delimiter\n");
|
||||
printf ("usage: cut [FLAG] FILE\n");
|
||||
printf ("FLAG can be:\n");
|
||||
printf (
|
||||
" -d C split each line based on the character C (default ' ')\n");
|
||||
printf (" -f N print the Nth field (1 is first, default 1)\n");
|
||||
printf ("If no FILE specified, read from STDIN\n");
|
||||
}
|
||||
Reference in New Issue
Block a user