Name

ftell

Synopsis

Obtains the current file access position

#include <stdio.h>
longftell( 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.

Tip

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

Example

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 );
}
do
{
  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] ); else lineno++; if ( ! fgets(sLine,MAX_LINE,fp )) // Read next line from file. { break; } } while ( strstr( sLine, argv[1] ) == NULL ); // Test for argument in sLine. /* Dropped out of loop: Found search keyword or EOF */ if ( feof(fp) || ferror(fp) ) { fprintf( stderr,"Unable to find "%s" in %s\n", argv[1], argv[2] ); rewind(fp); } else { printf( "%s (%d): %s\n", argv[2], lineno, sLine ); fseek( fp, lOffset, 0 ); // Set file pointer at beginning ...

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.