HP C/iX Library Reference Manual (30026-90004)
184 Chapter5
HP C/iX Library Function Descriptions
fseek
Example
The following program uses the ftell() and fseek() functions. The program prints each
line of an n-line file in this order: line 1, line n, line 2, line n-1, line 3, and so on.
#include <stdio.h>
main(argc, argv)
int argc;
char *argv[ ];
{
char line[256];
int newlines;
long front, rear, ftell();
FILE *fp;
front = 0;
rear = 0;
if(argc < 2) {
fprintf(stderr, "Usage: print filename\n");
exit(1);
}
fp = fopen(argv[1], "r");
if(fp == NULL) {
fprintf(stderr, "Can't open %s.\n", argv[1]);
exit(1);
}
newlines = countnl(fp) % 2;
fseek(fp, 0, 2);
rear = ftell(fp);
while(front < rear) {
fseek(fp, front, 0);
fgets(line, 256, fp);
fputs(line, stdout);
front = ftell(fp);
findnl(fp, rear);
rear = ftell(fp);
if(newlines == 1) {
if(rear <= front)
break;
}
fgets(line, 256, fp);
fputs(line, stdout);
}
exit(0);
}
countnl(fp)
FILE *fp;