问题描述
我想使用c.
最好的方法是什么?
我应该如何开始?
推荐答案
,如果您想 parse XML,而不仅仅是将其读成一个缓冲区(这些内容不是XML特定的,请参见Christoph's and 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; }
在Unix机器上,通常会与以下内容进行编译:
% gcc -o read-xml $(xml2-config --cflags) -Wall $(xml2-config --libs) read-xml.c
其他推荐答案
是否正在将文件内容读为单个简单的缓冲区真的您想做什么? XML文件通常在那里进行解析,您可以使用 libxml2 这样做来执行此操作.但值得注意的是,在c)中实现.
其他推荐答案
希望有没有错误的ISO-C代码来读取文件的内容并添加'\ 0'char:
#include <stdlib.h> #include <stdio.h> long fsize(FILE * file) { if(fseek(file, 0, SEEK_END)) return -1; long size = ftell(file); if(size < 0) return -1; if(fseek(file, 0, SEEK_SET)) return -1; return size; } size_t fget_contents(char ** str, const char * name, _Bool * error) { FILE * file = NULL; size_t read = 0; *str = NULL; if(error) *error = 1; do { file = fopen(name, "rb"); if(!file) break; long size = fsize(file); if(size < 0) break; if(error) *error = 0; *str = malloc((size_t)size + 1); if(!*str) break; read = fread(*str, 1, (size_t)size, file); (*str)[read] = 0; *str = realloc(*str, read + 1); if(error) *error = (size != (long)read); } while(0); if(file) fclose(file); return read; }
相关问答
相关标签/搜索