htslib icon indicating copy to clipboard operation
htslib copied to clipboard

Multiple stdout htsFile's result in no output

Open dancooke opened this issue 7 years ago • 3 comments

It appears it's only possible to create a single working stdout htsFile instance in a single execution, even if only one is actually open. Writing to a second instance results in no output to stdout. For example, uncommenting the two lines below results in no output to stdout:

#include "htslib/vcf.h"

int main()
{
    auto bcf = bcf_open("-", "[w]");
    // hts_close(bcf);
    // bcf = bcf_open("-", "[w]");
    const auto header = bcf_hdr_init("w");
    bcf_hdr_write(bcf, header);
    hts_close(bcf);
    bcf_hdr_destroy(header);
}

dancooke avatar Oct 23 '17 10:10 dancooke

Yes, once you've closed the stdout file descriptor, you can't reopen it again. What are you trying to do here? Trying to write two BCF files to stdout is unlikely to work anyway, as you'll get an extra header in the middle which would confuse the BCF reader.

daviesrob avatar Oct 23 '17 10:10 daviesrob

I can see the logic of that if stdout has already been written to, but here it is just opened and closed again. I think this is pretty reasonable usage; you might have a bunch of checks at startup, which just involve opening and closing files, to test for exceptions etc.

dancooke avatar Oct 23 '17 10:10 dancooke

I'm not sure exactly what checks you're planning to make, but if you're trying to test if files can be opened then it would be risky to assume that they will remain that way until you try to use them for real. It's quite possible for files to disappear or be renamed between checking and opening.

Your use of auto suggests that you're programming in C++. Remember that HTSlib is written in C. It will not throw exceptions, and you need to check the return values of all function calls.

We could make hopen_fd_stdinout() copy the file descriptor with dup() first, which would allow the original stdout to stay open after calling hclose(). I think some discussion will be needed first though, to decide if it is a good idea.

daviesrob avatar Oct 23 '17 15:10 daviesrob