C programming task, html source file

2019-03-03 18:03发布

问题:

So I have this task: I have a source file of, for example news website, in which there are meta tags like <meta name="author" content="Go Outside">. And, as you understand, that source file contains a lot of information. My task is to find that meta author tag and print out to the screen content of that meta tag, now it would be "Go Outside". I have no idea how to even start doing this. I had one idea to scan like 18 chars, and check if that is required meta tag, but that doesn't work as I thought:

   while(feof(src_file) == 0){
      char key[18];
      int i = 0;
      while (i < 18 && (feof(src_file) == 0)){
         key[i] = fgetc(src_file);
         printf("%c", key[i]);
         i++;
      }
      printf("\n%s", key);
   }

The problem is that it prints out rubbish at this line.

Your help would be appreciated since I have been working and studying for 10 hours straight, you might be able to save me from going mad. Thanks.

回答1:

You are missing to zero-terminate the char-array to enable it to be handle as a string before printing it.

Mod you code either like so:

...
{
  char key[18 + 1]; /* add one for the zero-termination */
  memset(key, 0, sizeof(key)); /* zero out the whole array, so there is no need to add any zero-terminator in any case */ 
  ...

or like so:

...
{
  char key[18 + 1]; /* add one for the zero-termination */

  ... /* read here */

  key[18] = '\0'; /* set zero terminator */
  printf("\n%s", key);
  ...

Update:

As mentioned in my comment to your question there is "another story" related to the way feof() is used, which is wrong.

Please see that the read loop is ended only after an EOF had been already been read in case of an error or a real end-of-file. This EOF pseudo character, then is added to the character array holdling the reads' result.

You might like to use the following construct to read:

{
  int c = 0;
  do
  {
    char key[18 + 1];
    memset(key, 0, sizeof(key));

    size_t i = 0;
    while ((i < 18) && (EOF != (c = fgetc(src_file))))
    {
       key[i] = c;
       printf("%c", key[i]);
       i++;
    }

    printf("\n%s\n", key);
  } while (EOF != c);
}
/* Arriving here means fgetc() returned EOF. As this can either mean end-of-file was
   reached **or** an error occurred, ferror() is called to find out what happend: */
if (ferror(src_file))
{
  fprintf(stderr, "fgetc() failed.\n");
}

For a detailed discussion on this you might like to read this question and its answers.



标签: html c task