c语言编写程序读取网页文件(例如:a.htm),找出标题内容以及在文件中行数写入文件result.txt中
时间: 2024-02-18 17:06:31 浏览: 23
好的,这里提供一个使用C语言实现的程序,同样需要使用第三方库libxml2来解析HTML文件。需要注意的是,这个程序只能在Linux系统下运行。
首先,我们需要安装libxml2库,你可以使用以下命令安装:
```
sudo apt-get install libxml2-dev
```
接下来,我们可以编写程序:
```c
#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main() {
// 读取HTML文件
FILE *fp;
char *filename = "a.htm";
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file: %s\n", filename);
return 1;
}
fseek(fp, 0L, SEEK_END);
int filesize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char *html = malloc(filesize + 1);
fread(html, sizeof(char), filesize, fp);
fclose(fp);
// 解析HTML文件
xmlDocPtr doc;
xmlNodePtr node;
doc = xmlReadMemory(html, filesize, "noname.xml", NULL, 0);
if (doc == NULL) {
printf("Failed to parse document\n");
return 1;
}
node = xmlDocGetRootElement(doc);
// 找到标题内容
xmlNodePtr title_node;
title_node = xmlGetFirstElementChild(node);
while (title_node != NULL && strcmp((char *)title_node->name, "title") != 0) {
title_node = xmlGetNextElementSibling(title_node);
}
if (title_node == NULL) {
printf("Failed to find title\n");
return 1;
}
char *title = (char *)xmlNodeListGetString(doc, title_node->xmlChildrenNode, 1);
// 找到行数
int lines = 0;
char *pch = strchr(html, '\n');
while (pch != NULL) {
lines++;
pch = strchr(pch+1, '\n');
}
// 写入结果文件
FILE *fp_out;
char *filename_out = "result.txt";
fp_out = fopen(filename_out, "w");
if (fp_out == NULL) {
printf("Failed to open file: %s\n", filename_out);
return 1;
}
fprintf(fp_out, "Title: %s\nLines: %d", title, lines);
fclose(fp_out);
// 释放内存
free(html);
xmlFree(title);
xmlFreeDoc(doc);
return 0;
}
```
这个程序会读取名为a.htm的文件,解析其中的HTML代码,并找到标题内容和行数,然后将结果写入名为result.txt的文件中。你只需要将a.htm文件放在程序所在的目录下,然后编译运行程序即可。