Created
March 23, 2017 14:44
-
-
Save Leandros/59c95ce4bb50d6661aea42eff98f9cc5 to your computer and use it in GitHub Desktop.
tail -1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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