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

后端 未结 8 899
逝去的感伤
逝去的感伤 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:41

    Suggestion: Use memory mapping

    This has the potential to cut down on useless copying of the data. The trick is to ask the OS for what you want, instead of doing it. Here's an implementation I made earlier:

    mmap.h

    #ifndef MMAP_H
    #define MMAP_H
    
    #include 
    
    struct region_t {
      void *head;
      off_t size;
    };
    
    #define OUT_OF_BOUNDS(reg, p) \
      (((void *)(p) < (reg)->head) || ((void *)(p) >= ((reg)->head)+(reg)->size))
    
    #define REG_SHOW(reg) \
      printf("h: %p, s: %ld (e: %p)\n", reg->head, reg->size, reg->head+reg->size);
    
    struct region_t *do_mmap(const char *fn);
    #endif
    

    mmap.c

    #include 
    
    #include   /* open lseek             */
    #include    /* open                   */
    #include       /* open                   */
    #include      /*      lseek             */
    #include    /*            mmap        */
    
    #include "mmap.h"
    
    struct region_t *do_mmap(const char *fn)
    {
      struct region_t *R = calloc(1, sizeof(struct region_t));
    
      if(R != NULL) {
        int fd;
    
        fd = open(fn, O_RDONLY);
        if(fd != -1) {
          R->size = lseek(fd, 0, SEEK_END);
          if(R->size != -1) {
            R->head = mmap(NULL, R->size, PROT_READ, MAP_PRIVATE, fd, 0);
            if(R->head) {
              close(fd); /* don't need file-destructor anymore. */
              return R;
            }
            /*                no clean up of borked (mmap,) */
          }
          close(fd);   /* clean up of borked (lseek, mmap,) */
        }
        free(R); /* clean up of borked (open, lseek, mmap,) */
      }
      return NULL;
    }
    

提交回复
热议问题