C编程任务,html源文件



所以我有这个任务:我有一个源文件,例如新闻网站,其中有像<meta name="author" content="Go Outside">这样的元标签。正如你所理解的,源文件包含了很多信息。我的任务是找到元作者标签,并打印出该元标签的屏幕内容,现在它将是"走出去"。我都不知道该怎么开始。我有一个想法来扫描像18个字符,并检查是否需要元标签,但这并不像我想的那样工作:

   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);
   }

问题是它在这一行打印出了垃圾。

我已经连续工作和学习了10个小时了,你的帮助会很感激的,你也许能把我从疯狂中拯救出来。谢谢。

您缺少零终止char -数组,以便在打印它之前将其作为字符串处理。

像这样修改你的代码:

...
{
  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 */ 
  ...

或类似的:

...
{
  char key[18 + 1]; /* add one for the zero-termination */
  ... /* read here */
  key[18] = ''; /* set zero terminator */
  printf("n%s", key);
  ...

更新:

正如我在对你的问题的评论中提到的,有"另一个故事"与feof()的使用方式有关,这是错误的。

请注意,读取循环只在EOF已经被读取之后才结束,以防出现错误或真正的文件结束。这个EOF伪字符,然后被添加到保存读取结果的字符数组中。

您可能喜欢使用以下结构来读取:

{
  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%sn", 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");
}

关于这方面的详细讨论,你可能会喜欢阅读这个问题及其答案

最新更新