Wednesday, March 3, 2010

Samtools C example

A simple samtools C api example. This program reads the bam file provided in the first argument and dumps the contents:

#include <stdlib.h>
#include <stdio.h>

#include "bam.h"
#include "sam.h"

int main(int argc, char *argv[]) {

samfile_t *fp_in = NULL;
bam1_t *b=NULL;

fp_in = samopen(argv[1], "rb", 0);

if(NULL == fp_in) {
printf("Could not open file\n");
}

b = bam_init1();
int pos=0;
int lastpos=0;

while(samread(fp_in, b) > 0) {
lastpos = pos;
pos = b->core.pos;

if(pos != lastpos) {
printf("tid : %d\n",b->core.tid);
printf("pos : %d\n",b->core.pos);
char *name = bam1_qname(b);
char *qual = bam1_qual(b);

int n=0;
char *qseq = (char *) malloc(b->core.l_qseq+1);
char *s = bam1_seq(b);
for(n=0;n<(b->core.l_qseq);n++) {
char v = bam1_seqi(s,n);
qseq[n] = bam_nt16_rev_table[v];
}
qseq[n] = 0;

printf("name : %s\n",name);
printf("qseq : %s\n",qseq);
//printf("s cigar: %s\n",cigar);

printf("qual :");
for(n=0;n<(b->core.l_qseq);n++) {
printf(" %d",qual[n]);
}
printf("\n");
}
bam_destroy1(b);
b = bam_init1();
}
bam_destroy1(b);

samclose(fp_in);
return 0;
}

No comments: