Skip to content

Instantly share code, notes, and snippets.

@gordinmitya
Created November 5, 2022 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordinmitya/2146389b9c3b1c1ecaf94648ea15da1e to your computer and use it in GitHub Desktop.
Save gordinmitya/2146389b9c3b1c1ecaf94648ea15da1e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
struct flags
{
int b, e, n, s, t, u, v;
} f = {0};
enum states
{
new_line,
wait4content,
content,
};
int line_num = 0;
void println()
{
if (f.b)
{
if (f.e)
{
printf(" \t");
}
}
else if (f.n)
{
printf("%6d\t", ++line_num);
}
if (f.e)
{
printf("$");
}
printf("\n");
}
int main(int argc, char **argv)
{
char c;
while ((c = getopt(argc, argv, "benstvET")) != -1)
{
switch (c)
{
case 'b':
f.b = 1;
break;
case 'n':
f.n = 1;
break;
case 's':
f.s = 1;
break;
case 'e':
f.e = 1;
f.v = 1;
break;
case 't':
f.t = 1;
f.v = 1;
break;
case 'v':
f.v = 1;
break;
case 'E':
f.e = 1;
break;
case 'T':
f.t = 1;
break;
default:
exit(1);
}
}
for (int argind = optind; argind < argc; ++argind)
{
char const *infile = "-";
if (argind < argc)
infile = argv[argind];
FILE *fptr;
if ((strcmp((infile), ("-")) == 0))
{
fptr = freopen(NULL, "r", stdin);
}
else
{
fptr = fopen(infile, "r");
}
if (fptr == NULL)
{
// printf("mycat: cannot open file: %s\n", infile);
exit(1);
}
int state = new_line;
while ((c = getc(fptr)) != EOF)
{
if (state == wait4content)
{ // s
if (c == '\n')
continue;
else
{
println();
state = new_line;
}
}
if (state == new_line)
{
if (c == '\n')
{
if (f.s)
{
state = wait4content;
continue;
}
println();
}
else
{
if (f.b || f.n)
{
printf("%6d\t", ++line_num);
}
state = content;
}
}
if (state == content)
{
if (c == '\n')
{
if (f.e)
{
printf("$");
}
printf("\n");
state = new_line;
continue;
}
else
{
int nonPrintable = (c >= 0 && c < 32) || (c == 127);
if (c == '\t')
{
if (f.t)
{
printf("^I");
}
else
{
printf("\t");
}
}
else if (f.v && nonPrintable)
{
if (c == 127)
{
printf("^?");
}
else
{
printf("^%c", c + 64);
}
}
else
{
printf("%c", c);
}
}
}
}
if (state == wait4content)
{
println();
}
fclose(fptr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment