如果你想解析 XML,不只是将它读入缓冲区(某些不是特定于XML的,请参阅Christoph和Baget的答案),你可以使用例如libxml2:
#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
int main(int argc, char **argv) {
xmlDoc *document;
xmlNode *root, *first_child, *node;
char *filename;
if (argc < 2) {
fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
return 1;
}
filename = argv[1];
document = xmlReadFile(filename, NULL, 0);
root = xmlDocGetRootElement(document);
fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
first_child = root->children;
for (node = first_child; node; node = node->next) {
fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
}
fprintf(stdout, "...\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在Unix机器上,您通常使用以下代码编译以上内容:
% gcc -o read-xml $(xml2-config --cflags) -Wall $(xml2-config --libs) read-xml.c
Run Code Online (Sandbox Code Playgroud)
您可以使用 stat() 函数来获取文件大小。然后在使用 fread 读取文件后使用 malloc 分配一个缓冲区。
代码将是这样的:
struct stat file_status;
char *buf = NULL;
FILE * pFile;
stat("tmp.xml", &file_status);
buf = (char*)malloc(file_status.st_size);
pFile = fopen ("tmp.xml","r");
fread (buf,1,file_status.st_size,pFile);
fclose(pFile);
Run Code Online (Sandbox Code Playgroud)