|
|
#include <stdio.h>int fgetpos(stream, pos) FILE *stream; fpos_t *pos;
ANSI X3.159-1989 Programming Language -- C
.
#include <stdio.h>FILE *stream; fpos_t position[]; int val, i; char fcontents[13]; /* buffer for full contents of file1 */ char writein1[14]= "Hello world!\n"; char writein2[8]= "there.\n";
main() { if ((stream = fopen("file1","w+")) == NULL) /* open file1 */ { perror("fopen"); printf ("Trouble opening file\n"); } else /* write in 1st string */ fwrite(writein1,sizeof(char),13,stream);
position=0; fsetpos(stream, &position); /*reset file to beginning */
fread(fcontents, sizeof(char), 13, stream); /* read contents */ printf("%s", fcontents); /* and print it */
position=0; fsetpos(stream, &position); /*reset file to beginning */
fread(fcontents, sizeof(char), 5, stream); /* read "Hello" */ if (fgetpos(stream, &position) != 0) /* Save current position */ perror("fgetpos error");
fread(fcontents, sizeof(char), 8, stream); /* read some more */ if (fsetpos(stream, &position) != 0) /* Return to saved position */ perror("fsetpos error");
/* Overwrite file from this position with the word "there" */
fwrite(writein2, sizeof(char), 8, stream);
position=0; fsetpos(stream, &position); /*reset file to beginning */ fread(fcontents, sizeof(char), 13, stream); printf("%s", fcontents); /* print contents */
}
This program opens a file named file1 and prints ``Hello world!'' It then outputs the file contents on screen. Next, it reads the first five characters in the file hello and calls fgetpos to find and save the file position pointer. After performing another read, the program calls fsetpos to restore the file pointer to the saved position.