c - 使用 C 提取 Wiki 链接

标签 c pointers segmentation-fault string.h

我需要编写一个程序来读取维基百科源文件并提取所有指向其他网页的链接。所有的网页看起来都像例子:

<a href="/wiki/PageName" title="PageName">Chicken</a>

我基本上需要将/wiki/之后的 PageName 与标题匹配,如果它们相同,如上,则仅在终端上显示 PageName。

但是,下面的应该不会被匹配,因为它和上面的格式不一样: <a href="http://chicken.com>Chicken</a> (这是维基百科上一个普通网站的链接) <a href="/wiki/Chicken >Chicken</a >(缺少标题=部分) 我试图实现的输出看起来像这样:

Example output I am trying to achieve

我已经在这方面工作了很长一段时间,并且能够做到以下几点:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
  FILE * file;
  file = fopen(argv[1], "r");

  char line[512];
  char* search;

  while(!feof(file)){
    fgets(line,512,file);

    search = strstr( line, "<a href=\"/wiki/");

    if(search != NULL){
        puts(search);
    }
  }
}

代码只过滤到/wiki/但我从这里开始一片空白。我尝试了很多搜索但无法找到线索。帮助将不胜感激。

最佳答案

您可以使用 while(fgets(line,512,file)) 代替 while(!feof(file)) 并通过添加几个验证您的最终代码预期输出看起来像,

#ifdef  _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif //  MSC

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE * file;

    if (argc != 2)
    {
        return -1;
    }

    file = fopen(argv[1], "r");

    if (!file)
    {
        return -1;
    }
    char line[512];
    char* search;

    while (fgets(line, 512, file)) {
        search = strstr(line, "<a href=\"/wiki/");

        if (search != NULL) {
            char *title = _strdup(search);
            if (title)
            {
                char* start = strstr(title, ">");
                char* end = strstr(start, "<");
                if (end)
                {
                    *end = 0;
                }
                if (strlen(start) >= 2)
                {
                    puts(start + 1);
                }
                free(title);
                title = 0;
            }
        }
    }
    fclose(file);
    file = NULL;
    return 0;
}

关于c - 使用 C 提取 Wiki 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713494/

相关文章:

java - C/objC/C++/Java 编译器

c - C 中使用多个分离线程的内存泄漏

c++ - 当我在 C++ 中对未初始化的指针调用 "delete"时会发生什么?

php 因对象过多而崩溃

c - c 中的方形图案

Xcode cs50.h 中的 C 问题

c++ - 存储指针值需要多少位?

ios - 使用 iOS Swift 将指针值保存在 parse.com 中

c++ - c++构造函数中的段错误

C++ 继承 : virtual member needs redeclaring?