C Language and Libraries Help (clang.hlp) (Table of Contents; Topic list)
SEEK.C
                                             Up Contents Index Back
─────Run-Time Library───────────────────────────────────────────────────────
 
/* SEEK.C illustrates low-level file I/O functions including:
 *      _filelength      _lseek           _tell
 */
 
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <fcntl.h>          /* _O_ constant definitions */
#include <process.h>
 
void error( char *errmsg );
 
void main()
{
    int handle, ch;
    unsigned count;
    long position, length;
    char buffer[2], fname[80];
 
    /* Get file name and open file. */
    do
    {
        printf( "Enter file name: " );
        gets( fname );
        handle = _open( fname, _O_BINARY | _O_RDONLY );
    } while( handle == -1 );
 
    /* Get and print length. */
    length = _filelength( handle );
    printf( "\nFile length of %s is: %ld\n\n", fname, length );
 
    /* Report the character at a specified position. */
    do
    {
        printf( "Enter integer position less than file length: " );
        scanf( "%ld", &position );
    } while( position > length );
 
    _lseek( handle, position, SEEK_SET );
    if( _read( handle, buffer, 1 ) == -1 )
        error( "Read error" );
    printf( "Character at byte %ld is ASCII %u ('%c')\n\n",
            position, *buffer, *buffer );
 
    /* Search for a specified character and report its position. */
    _lseek( handle, 0L, SEEK_SET);           /* Set to position 0 */
    printf( "Type character to search for: " );
    ch = _getche();
 
    /* Read until character is found. */
    do
    {
        if( (count = _read( handle, buffer, 1 )) == -1 )
            error( "Read error" );
    } while( (*buffer != (char)ch) && count );
 
    /* Report the current position. */
    position = _tell( handle );
    if( count )
        printf( "\nFirst ASCII %u ('%c') is at byte %ld\n",
                ch, ch, position );
    else
        printf( "\nASCII %u ('%c') not found\n", ch, ch );
    _close( handle );
    exit( 0 );
}
 
void error( char *errmsg )
{
    perror( errmsg );
    exit( 1 );
}
                                    -♦-