编写程序XMLtoTXT实现自动将XML文件email.xml转换为文本文件email.txt的功能。命令行格式为:XMLtoTXTemail.xmlemail.txt,用C语言或C++实现
时间: 2024-05-02 20:16:25 浏览: 25
以下是用C语言实现的XMLtoTXT程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1000
int main(int argc, char *argv[])
{
if (argc != 3) {
printf("Usage: %s input.xml output.txt\n", argv[0]);
return 1;
}
char *input_filename = argv[1];
char *output_filename = argv[2];
// 打开输入文件
FILE *input_file = fopen(input_filename, "r");
if (input_file == NULL) {
printf("Error: cannot open file %s\n", input_filename);
return 1;
}
// 打开输出文件
FILE *output_file = fopen(output_filename, "w");
if (output_file == NULL) {
printf("Error: cannot create file %s\n", output_filename);
return 1;
}
// 读取输入文件,将XML标签去掉,只保留文本内容
char line[MAX_LINE_LENGTH];
while (fgets(line, MAX_LINE_LENGTH, input_file) != NULL) {
int len = strlen(line);
if (line[len-1] == '\n') {
line[len-1] = '\0';
}
char *start = line;
while ((start = strchr(start, '<')) != NULL) {
char *end = strchr(start, '>');
if (end != NULL) {
memmove(start, end+1, strlen(end+1)+1);
} else {
break;
}
}
fprintf(output_file, "%s\n", line);
}
fclose(input_file);
fclose(output_file);
return 0;
}
```
要使用该程序,可以在命令行中键入以下命令:
```bash
XMLtoTXT email.xml email.txt
```
其中,email.xml是要转换的XML文件的文件名,email.txt是输出文本文件的文件名。