9.14. Random access functionsThe file I/O routines all work in the same way; unless the user takes
explicit steps to change the file position indicator, files will be read and
written sequentially. A read followed by a write followed by a read (if the
file was opened in a mode to permit that) will cause the second read to
start immediately following the end of the data just written. (Remember
that Three types of function exist which allow the file position indicator to be examined or changed. Their declarations and descriptions follow. #include <stdio.h> /* return file position indicator */ long ftell(FILE *stream); int fgetpos(FILE *stream, fpos_t *pos); /* set file position indicator to zero */ void rewind(FILE *stream); /* set file position indicator */ int fseek(FILE *stream, long offset, int ptrname); int fsetpos(FILE *stream, const fpos_t *pos);
Note that for
For both functions, on success, zero is returned; on failure, non-zero is returned and errno is set. 9.14.1. Error handlingThe standard I/O functions maintain two indicators with each open stream to show the end-of-file and error status of the stream. These can be interrogated and set by the following functions: #include <stdio.h> void clearerr(FILE *stream); int feof(FILE *stream); int ferror(FILE *stream); void perror(const char *s);
#include <stdio.h>
#include <stdlib.h>
main(){
fclose(stdout);
if(fgetc(stdout) >= 0){
fprintf(stderr, "What - no error!\n");
exit(EXIT_FAILURE);
}
perror("fgetc");
exit(EXIT_SUCCESS);
}
/* Result */
fgetc: Bad file numberExample 9.8Well, we didn't say that the message had to be very meaningful! |
The C BookThis book is published as a matter of historical interest. Please read the copyright and disclaimer information. GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested. |
|
West Yorkshire Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday South East Regional Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday Please note: |