从缓冲区C读取

时间:2012-02-25 10:47:33

标签: c linux curl libcurl

我正在尝试创建一个简单的c程序,它从网页中删除HTML并保留文本。到目前为止,我已经提出了下面的代码。它使用cURL获取网页的内容并将其写入文件。如何通过内存缓冲区删除所有HTML标记并将文本输出到终端或文件?

#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#define WEBPAGE_URL "http://homepages.paradise.net.nz/adrianfu/index.html"
#define DESTINATION_FILE "/home/acwest/data.txt"

size_t write_data( void *ptr, size_t size, size_t nmeb, void *stream)
{
 return fwrite(ptr,size,nmeb,stream);
}

int main()
{
 int in_tag = 0;
 char * buffer;
 char c;
 long lSize;
 size_t result;

 FILE * file = fopen(DESTINATION_FILE,"w+");
 if (file==NULL) {
fputs ("File error",stderr); 
exit (1);
}

 CURL *handle = curl_easy_init();
 curl_easy_setopt(handle,CURLOPT_URL,WEBPAGE_URL); /*Using the http protocol*/
 curl_easy_setopt(handle,CURLOPT_WRITEFUNCTION, write_data);
 curl_easy_setopt(handle,CURLOPT_WRITEDATA, file);
 curl_easy_perform(handle);
 curl_easy_cleanup(handle);

 // obtain file size:
 fseek (file, 0, SEEK_END);
 lSize = ftell (file);
 rewind (file);

 // allocate memory to contain the whole file:
 buffer = (char*) malloc (sizeof(char)*lSize);
 if (buffer == NULL) {
fputs ("Memory error",stderr); 
exit (2);
}

 // copy the file into the buffer:
 result = fread (buffer,1,lSize,file);
 if (result != lSize) {
fputs ("Reading error",stderr); 
exit (3);
}
}

1 个答案:

答案 0 :(得分:0)

Curl无法帮助您解析HTML,这是一项复杂的任务。您可以阅读语言规范并编写解析器。在http://www.mbayer.de/html2text/有一个开源C ++项目,在https://github.com/aaronsw/html2text有一个python脚本。您还可以从命令行安装和使用html2text,或者从您的c代码执行它。

相关问题