A typical VCF file has:


I would like to use htslib in C++ to read it. My attempt:

htsFile *fp = bcf_open("my.vcf", "r");
bcf_hdr_t *hdr = bcf_hdr_read(fp); 

In https://github.com/samtools/htslib/blob/develop/htslib/vcf.h, I'm not able to find a function that can do that for me.

How to read chr1 and 248956422 in C++?

  • $\begingroup$ As far as I can tell, the (internal) function bcf_hdr_parse_line does that. It returns an object x of type bcf_hrec_t*, for which strcmp(x->key, "contig") == 0) for your lines. You can then access the x->keys and x->vals. Untested. $\endgroup$ Feb 28, 2018 at 10:49
  • $\begingroup$ @KonradRudolph Can I use it externally properly? Without hacking? $\endgroup$
    – ABCD
    Feb 28, 2018 at 11:03
  • $\begingroup$ Depends on what you mean by “properly”. Since the API isn’t properly documented anyway, the distinction between external and internal functions is somewhat fluid. It might break with future versions of htslib, if that’s what you’re concerned about. $\endgroup$ Feb 28, 2018 at 11:13
  • $\begingroup$ @KonradRudolph Yeah. Breaking with future versions is my concern. If I see don't any other alternative, I might go with that or just parse the file myself. $\endgroup$
    – ABCD
    Feb 28, 2018 at 11:14

1 Answer 1

#include "htslib/vcf.h"

int main(int argc, char *argv[])
    htsFile *fp;
    bcf_hdr_t *hdr;
    bcf_idpair_t *ctg;
    int i;
    if (argc == 1) {
        fprintf(stderr, "Usage: print-ctg <in.vcf>\n");
        return 1;
    fp = vcf_open(argv[1], "r");
    hdr = vcf_hdr_read(fp);
    ctg = hdr->id[BCF_DT_CTG];
    for (i = 0; i < hdr->n[BCF_DT_CTG]; ++i)
        printf("%s\t%d\n", ctg[i].key, ctg[i].val->info[0]);
    return 0;

On stability: this use has been in htslib forever. In general, functions/structs/variables in the public headers are meant to be stable. However, there is no guarantee that future versions will always keep the same APIs.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.