I get way too carried away with these things sometimes:
Code:
itsme@itsme:~/C$ cat nlindex.c
// Creates an index file (nline.idx) that contains file offsets of
// newlines that exist in the input file.
//
// Usage: nlindex <input file>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void write_offset(FILE *fp, long offset)
{
fwrite(&offset, sizeof(offset), 1, fp);
}
int main(int argc, char **argv)
{
FILE *fpin, *fpout;
int c;
if(argc != 2)
{
fputs("Usage: nlindex <input file>", stderr);
exit(EXIT_FAILURE);
}
if(!(fpin = fopen(argv[1], "r")))
{
fprintf(stderr,
"Couldn't open '%s' for reading: %s\n", argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
if(!(fpout = fopen("nline.idx", "wb")))
{
fprintf(stderr,
"Couldn't open 'nline.idx' for writing: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
while((c = fgetc(fpin)) != EOF)
if(c == '\n')
write_offset(fpout, ftell(fpin) - 1);
fclose(fpin);
fclose(fpout);
return EXIT_SUCCESS;
}
Code:
itsme@itsme:~/C$ cat nlfirstchar.c
// Prints the first character of every line in the input file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv)
{
FILE *fptxt, *fpidx;
int c;
long offset;
if(argc != 2)
{
fputs("Usage: nlfirstchar <input file>\n", stderr);
exit(EXIT_FAILURE);
}
if(!(fptxt = fopen(argv[1], "r")))
{
fprintf(stderr,
"Couldn't open '%s' for reading: %s\n", argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
if(!(fpidx = fopen("nline.idx", "rb")))
{
fprintf(stderr,
"Couldn't open 'nline.idx' for reading: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if((c = fgetc(fptxt)) != EOF)
putchar(c);
while(fread(&offset, sizeof(offset), 1, fpidx))
{
fseek(fptxt, offset + 1, SEEK_SET);
if((c = fgetc(fptxt)) == EOF)
break;
putchar(c);
}
putchar('\n');
fclose(fptxt);
fclose(fpidx);
return EXIT_SUCCESS;
}
Code:
itsme@itsme:~/C$ cat forindex.txt
it's too much work to do it this way.
this is nuts.
somewhere, this might serve a purpose.
mildly entertaining anyway.
everyone's a critic.
800 llamas can fill a swimming pool.
600 could probably do it.
Code:
itsme@itsme:~/C$ ./nlindex forindex.txt
itsme@itsme:~/C$ ./nlfirstchar forindex.txt
itsme86
itsme@itsme:~/C$
Clever, no?
Anyway, this would make it easy to grab the 3rd offset from the index file, fseek() to that offset in the text file, and then use fgets() to read in that line.