home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap10 / view.c < prev   
Encoding:
C/C++ Source or Header  |  1988-04-06  |  2.2 KB  |  90 lines

  1. /* view.c  --  demonstrates lseek() by displaying  */
  2. /*             a file and moving around in it      */
  3.  
  4. #include <fcntl.h>           /* for open()         */
  5. #include <stdio.h>           /* for SEEK_CUR, etc. */
  6.  
  7. #define HUNK 512
  8. #define MOVE 512L
  9.  
  10. main(argc, argv)
  11. int argc;
  12. char *argv[];
  13. {
  14.     char ch, buf[HUNK];
  15.     long position = 0L;
  16.     int  bytes, eofflag = 0, fd_in;
  17.  
  18.     if (argc != 2)
  19.         {
  20.         fprintf(stderr, "Usage: view file\n");
  21.         exit(0);
  22.         }
  23.  
  24.     if ((fd_in = open(argv[1], O_RDONLY)) < 0)
  25.         {
  26.         fprintf(stderr, "\"%s\": Can't open.\n", argv[1]);
  27.         exit(1);
  28.         }
  29.  
  30.     for (;;)
  31.         {
  32.         bytes = read(fd_in, buf, HUNK);
  33.         if (bytes == 0)
  34.             {
  35.             if (! eofflag)
  36.                 {
  37.                 fprintf(stderr, "\n<<at end of file>>\n");
  38.                 ++eofflag;
  39.                 }
  40.             else
  41.                 exit(0);
  42.             }
  43.         else if (bytes < 0)
  44.             {
  45.             fprintf(stderr, "\"%s\": Error Reading.\n", argv[1]);
  46.             exit(1);
  47.             }
  48.         else
  49.             {
  50.             eofflag = 0;
  51.             position = lseek(fd_in, 0L, SEEK_CUR);
  52.             if (position == -1L)
  53.                 {
  54.                 fprintf(stderr, "\"%s\": Error Seeking.\n", argv[1]);
  55.                 exit(1);
  56.                 }
  57.             Print(buf, bytes);
  58.             do
  59.                 {
  60.                 ch = getch();
  61.                 if (ch == 'q' || ch == 'Q')
  62.                     exit(0);
  63.                 } while (ch != '+' && ch != '-');
  64.  
  65.             if (ch == '-')
  66.                 {
  67.                 position = lseek(fd_in, -2 * MOVE, SEEK_CUR);
  68.                 if (position == -1L)
  69.                     {
  70.                     fprintf(stderr, "\"%s\": Error Seeking.\n", argv[1]);
  71.                     exit(1);
  72.                     }
  73.                 }
  74.             }
  75.         }
  76. }
  77.  
  78. Print(char *buf, int cnt)
  79. {
  80.     int i;
  81.  
  82.     for (i = 0; i < cnt; ++i, ++buf)
  83.         {
  84.         if (*buf < ' ' && *buf != '\n' && *buf != '\t')
  85.             printf("^%c", *buf + '@');
  86.         else
  87.             putchar(*buf);
  88.         }
  89. }
  90.