How can I read an XML file into a buffer in C?

后端 未结 8 818
逝去的感伤
逝去的感伤 2021-02-01 11:03

I want to read an XML file into a char *buffer using C.

What is the best way to do this?

How should I get started?

8条回答
  •  抹茶落季
    2021-02-01 11:55

    Hopefully bug-free ISO-C code to read the contents of a file and add a '\0' char:

    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题