Skip to content

Instantly share code, notes, and snippets.

@Leandros
Created March 23, 2017 14:44
Show Gist options
  • Save Leandros/59c95ce4bb50d6661aea42eff98f9cc5 to your computer and use it in GitHub Desktop.
Save Leandros/59c95ce4bb50d6661aea42eff98f9cc5 to your computer and use it in GitHub Desktop.
tail -1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF 4096
int main(int argc, char **argv)
{
FILE *f;
int i, n, nl;
long o1, o2;
char buf[BUF];
if (argc != 2)
return 1;
f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_END);
o1 = (o1 = ftell(f)) < BUF ? o1 : BUF;
for (o2 = 0;;) {
fseek(f, o2 -= o1, SEEK_END);
fread(buf, 1, o1, f);
for (i = 0, n = -1; i < o1; ++i)
if (buf[i] == '\n')
nl = n, n = i;
if (n != -1)
break;
}
out:
{
char *l = malloc(n = -(o2 + nl) + 1);
fseek(f, (o2 + nl) + 1, SEEK_END);
fread(l, 1, n - 1, f);
l[n-1] = '\0';
printf("%s", l);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment