home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / file / seek.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-11-01  |  1.9 KB  |  73 lines

  1. /* SEEK.C illustrates low-level file I/O functions including:
  2.  *      filelength      lseek           tell
  3.  */
  4.  
  5. #include <io.h>
  6. #include <conio.h>
  7. #include <stdio.h>
  8. #include <fcntl.h>          /* O_ constant definitions */
  9. #include <process.h>
  10.  
  11. void error( char *errmsg );
  12.  
  13. main()
  14. {
  15.     int handle, ch;
  16.     unsigned count;
  17.     long position, length;
  18.     char buffer[2], fname[80];
  19.  
  20.     /* Get file name and open file. */
  21.     do
  22.     {
  23.         printf( "Enter file name: " );
  24.         gets( fname );
  25.         handle = open( fname, O_BINARY | O_RDONLY );
  26.     } while( handle == -1 );
  27.  
  28.     /* Get and print length. */
  29.     length = filelength( handle );
  30.     printf( "\nFile length of %s is: %ld\n\n", fname, length );
  31.  
  32.     /* Report the character at a specified position. */
  33.     do
  34.     {
  35.         printf( "Enter integer position less than file length: " );
  36.         scanf( "%ld", &position );
  37.     } while( position > length );
  38.  
  39.     lseek( handle, position, SEEK_SET );
  40.     if( read( handle, buffer, 1 ) == -1 )
  41.         error( "Read error" );
  42.     printf( "Character at byte %ld is ASCII %u ('%c')\n\n",
  43.             position, *buffer, *buffer );
  44.  
  45.     /* Search for a specified character and report its position. */
  46.     lseek( handle, 0L, SEEK_SET);           /* Set to position 0 */
  47.     printf( "Type character to search for: " );
  48.     ch = getche();
  49.  
  50.     /* Read until character is found */
  51.     do
  52.     {
  53.         if( (count = read( handle, buffer, 1 )) == -1 )
  54.             error( "Read error" );
  55.     } while( (*buffer != (char)ch) && count );
  56.  
  57.     /* Report the current position. */
  58.     position = tell( handle );
  59.     if( count )
  60.         printf( "\nFirst ASCII %u ('%c') is at byte %ld\n",
  61.                 ch, ch, position );
  62.     else
  63.         printf( "\nASCII %u ('%c') not found\n", ch, ch );
  64.     close( handle );
  65.     exit( 0 );
  66. }
  67.  
  68. void error( char *errmsg )
  69. {
  70.     perror( errmsg );
  71.     exit( 1 );
  72. }
  73.