HP C/iX Library Reference Manual (30026-90004)

Chapter 5 185
HP C/iX Library Function Descriptions
fseek
{
char c;
int count = 0;
while((c = getc(fp)) != EOF) {
if(c == '\n')
count++ }
rewind(fp);
return(count);
}
findnl(fp, offset)
FILE *fp;
long offset;
{
char c;
fseek(fp, (offset-2), 0);
while((c = getc(fp)) != '\n') {
fseek(fp, -2, 1);
}
}
This program uses the ftell() and fseek() functions to print lines from a file starting at
the beginning and the end of the file, and converging toward the center. The countnl()
function counts the number of lines in the file so the program can decide whether or not to
print a line in the final loop to prevent the middle line being printed twice in files with an
odd number of lines. The findnl() function searches backwards in the file for the next
newline character. When found, this positions the next I/O operation such that fgets()
gets the next line back from the end of the file.
All three types of seeks are represented in this program. The first fseek() of the program
is done relative to the end of the file. All other fseek() operations in the main program are
done relative to the beginning of the file. Finally, findnl() contains an fseek() that is
relative to the current position.
The example located in the fread() function description uses a structure that described
each employee, as shown below:
struct emp {
char name[40]; /* name */
char job[40]; /* job title */
long salary; /* salary */
char hire[6]; /* hire date */
char curve[2]; /* pay curve */
int rank; /* percentile ranking */
}
This function reads the data for 400 employees all at once. Suppose you want the program
to be selective, so that you can specify by employee number (1 through 400) which
employee's information you want. The following program fragment shows how to use