如何在C中将XML文件读入缓冲区?

Uca*_*oIt 5 c xml

我想将XML文件读入char *buffer使用C.

做这个的最好方式是什么?

我应该如何开始?

Nie*_*jou 7

将文件的内容读入单个,简单的缓冲区真的是你想要做的吗?XML文件通常需要解析,你可以使用像libxml2这样的库来实现,只是举一个例子(但值得注意的是,用C实现).


bor*_*yer 7

如果你想解析 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)


Bag*_*get 2

您可以使用 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)