codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
#include <stdio.h> #include <stdlib.h> /* get an array with line-startpositions (file-offsets) */ long readLineBegins(FILE *f,long **begins) { long ch=0L, mark=0L, num=0L; *begins = 0; do { if( ch=='\n' ) { *begins = realloc( *begins, ++num * sizeof(long) ); (*begins)[num-1] = mark; mark = ftell(f); } } while( (ch=fgetc(f))!=EOF ); if( mark<ftell(f) ) { *begins = realloc( *begins, ++num * sizeof(long) ); (*begins)[num-1]=mark; } return num; } /* output linenumber beg...end */ void workLineBlocks(FILE *f,long *begins,long beg,long end) { while( beg<=end ) { int ch; fsetpos( f, &begins[beg] ); /* set linestart-position */ printf("%ld:", ++beg ); while( (ch=fgetc(f))!=EOF && ch!='\n' && ch!='\r' ) putchar(ch); puts(""); } } int main() { FILE *f=fopen("file.txt","rb"); long *lineBegins, /* Array with line-startpositions */ lb = readLineBegins(f,&lineBegins); /* get number of lines */ workLineBlocks(f,lineBegins,lb-2,lb-1); /* out last two lines */ workLineBlocks(f,lineBegins,0,1); /* out first two lines */ fclose(f); free(lineBegins); return 0; }
Private
[
?
]
Run code
Submit