December 2005
Beginner to intermediate
618 pages
20h 19m
English
ftell
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.
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 );
}
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 ...Read now
Unlock full access