shell pipeline to reverse the order of lines.

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Sat Feb 16 08:50:38 AEST 1991


In article <9102151917.AA04419 at wendy-fate.UU.NET> kyle at UUNET.UU.NET (Kyle Jones) writes:
>    cat -n | sort -rn | sed 's/ *[0-9]*.//'

If you care so much about it, write it in C. This version is several
times faster than any of the other versions posted; it's even 50% faster
than the ``tac'' that comes with SunOS. It only works on files, though,
so you have to create a temporary file if you want to use it off a pipe.

---Dan

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
extern char *malloc();

main()
{
 char *s;
 int i;
 int j;
 struct stat st;

 if (fstat(0,&st) == -1) exit(1);
 if (!(s = malloc(st.st_size + 3))) exit(2);
 if (read(0,s,st.st_size) < st.st_size) exit(3);
 i = j = st.st_size - 1;
 do
  {
   if (s[i] == '\n')
    {
     if (fwrite(s + i + 1,1,j - i,stdout) < j - i) exit(4);
     j = i;
    }
  }
 while(i--);
 if (fwrite(s,1,j + 1,stdout) < j + 1) exit(4);
 exit(0);
}



More information about the Alt.sources.d mailing list