home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The C Users' Group Library 1994 August
/
wc-cdrom-cusersgrouplibrary-1994-08.iso
/
listings
/
v_11_05
/
1105101a
< prev
next >
Wrap
Text File
|
1993-03-09
|
2KB
|
66 lines
/* records.c: Illustrates file positioning */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXRECS 10
struct record
{
char last[16];
char first[11];
int age;
};
static char *get_field(char *, char *);
main()
{
int nrecs;
char s[81];
struct record recs[MAXRECS], recbuf;
FILE *f;
/* Carefully store records */
for (
nrecs = 0;
nrecs < MAXRECS && get_field("Last",s);
++nrecs
)
{
strncpy(recs[nrecs].last,s,15)[15] = '\0';
get_field("First",s);
strncpy(recs[nrecs].first,s,10)[10] = '\0';
get_field("Age",s);
recs[nrecs].age = atoi(s);
}
/* Write records to file */
if ((f = fopen("recs.dat","w+b")) == NULL)
return EXIT_FAILURE;
if (fwrite(recs,sizeof recs[0],nrecs,f) != nrecs)
return EXIT_FAILURE;
/* Position at last record */
fseek(f,(nrecs-1)*sizeof(struct record),SEEK_SET);
fread(&recbuf,1,sizeof(struct record),f);
printf("last: %s, first: %s, age: %d\n",
recbuf.last,recbuf.first,recbuf.age);
/* Position at first record */
rewind(f);
fread(&recbuf,1,sizeof(struct record),f);
printf("last: %s, first: %s, age: %d\n",
recbuf.last,recbuf.first,recbuf.age);
return EXIT_SUCCESS;
}
static char *get_field(char *prompt, char *buf)
{
/* Prompt for input field */
fprintf(stderr,"%s: ",prompt);
return gets(buf);
}