home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1995 April / Internet Tools.iso / infoserv / www / cern / src / extract_title.c.Z / extract_title.c
Encoding:
C/C++ Source or Header  |  1994-05-15  |  1.8 KB  |  86 lines

  1.  
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. typedef int BOOL;
  6. #define TRUE 1
  7. #define FALSE 0
  8.  
  9. main(argc, argv)
  10. int argc;
  11. char **argv;
  12. {
  13.     FILE *fp;
  14.     char filename[256];
  15.     char buffer[1024];
  16.     char *p;
  17.     BOOL found = FALSE;
  18.     BOOL tag = FALSE;
  19.     int lines = 0;
  20.  
  21.     if (argc != 3) {
  22.     fprintf(stderr, "\n\
  23. This program takes an HTML document and extracts to its stdout\n\
  24. the TITLE of the document, all in one line.\n\n\
  25. Usage:\n\
  26. \t%s directory filename\n\n", argv[0]);
  27.     exit(1);
  28.     }
  29.  
  30.     strcpy(filename, argv[1]);
  31.     if (*filename)
  32.       strcat(filename, "/");
  33.     strcat(filename, argv[2]);
  34.  
  35.     if (!(fp = fopen(filename, "r"))) {
  36.     fprintf(stderr, "%s: Unable to open file \"%s\"\n",
  37.         argv[0], filename);
  38.     exit(2);
  39.     }
  40.  
  41.     while (lines++ < 20 &&    /* Scan only first 20 lines */
  42.        NULL != (p = fgets(buffer, 1024, fp))) {
  43.     if (*p)
  44.         p[strlen(p)-1] = NULL;    /* Overwrite newline */
  45.     while (p && *p) {
  46.         if (tag) {
  47.         p = strchr(p, '>');
  48.         if (p) { 
  49.             p++;
  50.             tag = FALSE;
  51.         }
  52.         else continue;
  53.         }
  54.         if (found)
  55.         while (*p && *p != '<') fputc(*(p++), stdout);
  56.         else
  57.         while (*p && *p != '<') p++;
  58.         if (!*p) {
  59.         if (found)
  60.             fputc(' ', stdout);    /* We replace newline with space */
  61.         continue;
  62.         }
  63.         else if (!found && (!strncmp(p, "<TITLE>", 7) ||
  64.                 !strncmp(p, "<title>", 7) ||
  65.                 !strncmp(p, "<Title>", 7))) {
  66.         p += 7;
  67.         found = TRUE;
  68.         }
  69.         else if (found && (!strncmp(p, "</TITLE>", 8) ||
  70.                    !strncmp(p, "</title>", 8) ||
  71.                    !strncmp(p, "</Title>", 8))) {
  72.         fclose(fp);
  73.         fputc('\n', stdout);
  74.         exit(0);
  75.         }
  76.         else tag = TRUE;
  77.     } /* while stuff in buffer */
  78.     } /* while not EOF and not very many lines read */
  79.  
  80.     /* If we come here, the title was not found among */
  81.     /* the first few lines. */
  82.     printf("%s\n", argv[2]);  /* Then using filename */
  83.     fclose(fp);
  84. }
  85.  
  86.