Previous Page
Next Page


Obtains the current file access position

#include <stdio.h>
long ftell ( FILE *fp  );

The ftell( ) function returns the current access position in the file controlled by the FILE pointer argument. If the function fails to obtain the file position, it returns the value -1 and sets the errno variable to an appropriate positive value.

To save the access position in a multibyte stream, use the fgetpos( ) function, which also saves the stream's multibyte parsing state.


This example searches in a file, whose name is the second command-line argument, for a string, which the user can specify in the first command-line argument.

#define MAX_LINE 256

FILE *fp;
long lOffset = 0L;
char sLine[MAX_LINE] = "";
char *result = NULL;
int lineno = 0;
/* ... */
if ((fp = fopen(argv[2], "r")) == NULL)
  fprintf(stderr, "Unable to open file %s\n", argv[2]);
  exit( -1 );
  lOffset = ftell( fp );    // Bookmark the beginning of
                            // the line we're about to read.
  if ( -1L == lOffset )
    fprintf( stderr, "Unable to obtain offset in %s\n", argv[2] );

  if ( ! fgets( sLine, MAX_LINE, fp ) )   // Read next line from file.
    fprintf( stderr, "Unable to read from %s\n", argv[2] );
} while ( strstr( sLine, argv[1] ) == NULL ); // Test for argument in sLine.
/* Dropped out of loop: Found search keyword or EOF */
if ( feof( fp ))
    fprintf( stderr, "Unable to find \"%s\" in %s\n", argv[1], argv[2] );
      rewind( fp );
    printf( "%s (%d): %s\n", argv[2], lineno, sLine );
    fseek( fp, lOffset, 0 );    // Set file pointer at beginning of
                                // the line containing the keyword

The following example runs this program on its own source file, searching for a line containing the word "the". As you can see, the first occurrence of "the" is in line 22. The program finds that line and displays it:

tony@luna:~/ch17$ ./ftell the ftell.c
ftell.c (22):      lOffset = ftell(fp);    // Bookmark the beginning of

See Also

fgetpos( ), fsetpos( ), fseek( ), rewind( )

Previous Page
Next Page