Syntax
#include <stdio.h> long int ftell(FILE *stream);Description
ftell finds the current position of the file associated with stream. For a fixed-length binary file, the value returned by ftell is an offset relative to the beginning of the stream.
Note: For buffered text streams, ftell returns an incorrect file position if the file contains new-line characters instead of carriage-return line-feed combinations. Your file would only contain new-line characters if you previously used it as a binary stream. To avoid this problem, either continue to process the file as a binary stream, or use unbuffered I/O operations.
ftell returns the current file position. On error, ftell returns -1L and sets errno to a nonzero value.
This example opens the file myfile.dat for reading. It reads enough characters to fill half of the buffer and prints out the position in the stream and the buffer.
#include <stdio.h> #define NUM_ALPHA 26 #define NUM_CHAR 6 int main(void) { FILE *stream; int i; char ch; char buffer[NUM_ALPHA]; long position; if ((stream = fopen("myfile.dat", "r")) != NULL) { /* read into buffer */ for (i = 0; (i < NUM_ALPHA/2) && ((buffer[i] = fgetc(stream)) != EOF); ++i) if (i == NUM_CHAR-1) { /* We want to be able to position the file pointer to the character in position NUM_CHAR */ position = ftell(stream); printf("Current position of the file is stored.\n"); } buffer[i] = '\0'; fseek(stream, position, SEEK_SET); ch = fgetc(stream); /* get the character at position NUM_CHAR */ fclose(stream); } else perror("Error opening myfile.dat"); return 0; }Related Information