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.
ExampleThis 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.
{
fprintf( stderr, "Unable to read from %s\n", argv[2] );
break;
}
} 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 );
}
else
{
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 Alsofgetpos( ), fsetpos( ), fseek( ), rewind( ) |