Answers.Body: <p>The best solution is to reopen the file. For a coordinate sorted file you have the option to jump back to the start of the first chromosome with index but that is more complex, less flexible and won't be faster.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-06T15:53:53.750Z
Answers.LastActivityDate: 2023-06-06T15:53:53.750Z
Answers.UserDisplayName: user172818
Body: <p>I would like to read iteratively the same BAM file twice using <code>htslib</code>.</p>
  <p>My option is to use <code>hts_open</code>, <code>sam_hdr_read</code>, then <code>sam_read1</code> as much as needed to read the file until EOF.</p>
  <p>Is there a possibility to &quot;rewind&quot;, and use <code>sam_read1</code> again from the beginning of the file, without closing the file, destroying the object, and opening it again?</p>
  <hr />
  <p><strong>EDIT</strong></p>
  <p>My aim is group the reads by the barcode.  The first pass would allocate the specific sizes first (the number of reads by barcode), then store the reads.</p>
  <p>I know I could sort the reads first (using <code>samtools sort -t BX</code>), but I would like to skip this step using pre-allocation.</p>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-06-06T14:48:22.640Z
Comments.Text: @M__ Thanks, I edited the question.  I hope it helps!
Comments.UserDisplayName: unamourdeswann
Tags: <htslib>
Title: Reading same BAM file twice with htslib
ThreadText: # Reading same BAM file twice with htslib
  
  (Asked by: username_0 on 2023-06-06)
  
  I would like to read iteratively the same BAM file twice using `htslib`.
  
  My option is to use `hts_open`, `sam_hdr_read`, then `sam_read1` as much as needed to read the file until EOF.
  
  Is there a possibility to "rewind", and use `sam_read1` again from the beginning of the file, without closing the file, destroying the object, and opening it again?
  
  ---
  
  **EDIT**
  
  My aim is group the reads by the barcode. The first pass would allocate the specific sizes first (the number of reads by barcode), then store the reads.
  
  I know I could sort the reads first (using `samtools sort -t BX`), but I would like to skip this step using pre-allocation.
  
  **Tags:** htslib
  
  > **Comments:**
  > **username_0**: @M__ Thanks, I edited the question.  I hope it helps!  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2023-06-06. Score: 1 | Accepted answer
  
  The best solution is to reopen the file. For a coordinate sorted file you have the option to jump back to the start of the first chromosome with index but that is more complex, less flexible and won't be faster.
  
  
  ---
  
  