Module 12 · C++ for bioinformatics
12.1Reading FASTA and FASTQ
Read the two text formats that sequencing data comes in: multi-line FASTA records, FASTQ reads with Phred quality scores, mean quality and trimming, clear errors for malformed files with std::expected, and a faster reader that loads the whole file once.
On this page
Key terms
- read
- One piece of DNA as a sequencing machine reported it: a string of the letters
A,C,GandT(andNfor a base it couldn't call), usually 50 to a few thousand bases long. - FASTA
- A text format for sequences. Each record is a header line starting with
>, then the sequence, often split over several lines. - FASTQ
- A text format for reads. Each record is exactly four lines:
@and a name, the bases, a+line, and one quality character per base. - Phred quality score
- How sure the machine is of a base: a score
Qmeans the chance it's wrong is 10 to the power-Q/10. Q20 is 1 in 100, Q30 is 1 in 1,000. - Phred+33
- The way FASTQ stores a score as one printable character: the character's code minus 33.
!is Q0,5is Q20,?is Q30 andIis Q40. std::ifstream- An input stream that reads a file (from
<fstream>). It works likestd::cin:std::getlineand>>read from it. - quality trimming
- Cutting the low-quality bases off the end of a read before using it, because sequencing errors pile up there.
The next four lessons use C++ for bioinformatics: you’ll read sequencing data, pack DNA into bits and count k-mers, align sequences, and process millions of reads in parallel. It all starts with getting the data in. Sequencers and databases hand you plain text files in two formats, FASTA and FASTQ, and real files are big and sometimes broken. This lesson reads both formats, reports bad input with the line it’s on, and then reads faster by loading the whole file at once.
In 30 seconds
std::ifstream file(path);opens a file;std::getline(file, line)reads it one line at a time, just likestd::cin.- FASTA: a
>header, then sequence lines to join. FASTQ: four lines per read, with one quality character per base. - A quality character’s code minus 33 is its Phred score:
'I' - 33is 40. - Return
std::expectedfrom a parser, with the line number in the error, so a broken file gets a message the user can act on.
FASTA: a header and sequence lines
A FASTA record starts with a header line: >, an ID up to the first space, then an optional description that this reader drops. The sequence follows on one or more lines, until the next > or the end of the file. Here are three sequences in a file, and a program that reads them into a Record struct:
2 files, built together
#include <fstream>
#include <istream>
#include <print>
#include <string>
#include <vector>
struct Record {
std::string id;
std::string sequence;
};
std::vector<Record> read_fasta(std::istream& in) {
std::vector<Record> records;
std::string line;
while (std::getline(in, line)) {
if (line.starts_with('>')) {
std::size_t space = line.find(' ');
records.push_back({line.substr(1, space - 1), ""});
} else if (!records.empty()) {
records.back().sequence += line;
}
}
return records;
}
int main(int argc, char** argv) {
if (argc != 2) {
std::println("usage: app <file.fa>");
return 1;
}
std::ifstream file(argv[1]);
if (!file) {
std::println("can't open {}", argv[1]);
return 1;
}
for (const Record& r : read_fasta(file)) {
std::println("{}: {} bases", r.id, r.sequence.size());
}
}>lacZ beta-galactosidase, first bases
ATGACCATGATTACGGATTCACTGGCC
GTCGTTTTACAACGTCGTGACTGG
>probe1 short primer
GGCGCGCC
>gene3
ATATTTAABuild and run
g++ -std=c++23 -Wall -Wextra -Wpedantic main.cpp -o app ./app genes.fa
Output
lacZ: 51 bases probe1: 8 bases gene3: 8 bases
std::ifstream file(argv[1]);opens the file named on the command line. If that fails (no such file, no permission),if (!file)catches it. Without the check, the loop would read nothing, which looks like an empty file.read_fastatakes astd::istream&, the type every input stream shares, so it can also readstd::cinor text in memory. Sequence lines are joined onto the last record with+=.- When there’s no space,
findreturnsstd::string::npos, the largeststd::size_t.substrcuts the count down to what’s left, soline.substr(1, npos - 1)takes the whole rest of the line.
FASTQ: four lines per read
A sequencer reports more than bases: it says how sure it is of each one. FASTQ stores that in four lines per read: @ and the read’s name, the bases, a line starting with + (sometimes followed by the name again), and a quality line with one character per base. Each quality character is a Phred score stored as Phred+33: subtract 33 from the character’s code. The score Q says the chance the base is wrong is 10−Q/10:
#include <cmath>
#include <print>
#include <string_view>
for (char c : std::string_view("!+5?I")) {
int q = c - 33;
double error = std::pow(10.0, -q / 10.0);
std::println("{} Q{:<2} error chance {:g}", c, q, error);
}Output
! Q0 error chance 1 + Q10 error chance 0.1 5 Q20 error chance 0.01 ? Q30 error chance 0.001 I Q40 error chance 0.0001
std::pow(x, y) (from <cmath>) is x to the power y, and {:g} prints a double without trailing zeros. Codes below 33 are spaces and control characters, which is why the scale starts there: every score from 0 to 93 is one visible character.
Mean quality and trimming
A read’s mean quality is a quick way to judge it. Quality also tends to drop toward the end of a read, so tools cut off the end where scores fall below a threshold before using the bases. This trimmer drops bases from the end while their score is under 20:
#include <print>
#include <string>
#include <string_view>
double mean_quality(std::string_view quality) {
int total = 0;
for (char c : quality) {
total += c - 33;
}
return static_cast<double>(total) / static_cast<double>(quality.size());
}
void trim_end(std::string& sequence, std::string& quality, int min_quality) {
std::size_t keep = quality.size();
while (keep > 0 && quality[keep - 1] - 33 < min_quality) {
--keep;
}
sequence.resize(keep);
quality.resize(keep);
}
int main() {
std::string sequence = "ACGTTGCAACGT";
std::string quality = "IIIII???5+#!";
std::println("{} Q{:.1f}", sequence, mean_quality(quality));
trim_end(sequence, quality, 20);
std::println("{} Q{:.1f}", sequence, mean_quality(quality));
}Output
ACGTTGCAACGT Q26.8 ACGTTGCAA Q34.4
!, # and + (Q0, Q2 and Q10) are cut; 5 is exactly Q20, so it stays. Cut the sequence and the quality together, or they stop lining up. Real trimmers use a sliding window, so one good base in a bad stretch doesn’t stop the trim.
Reporting malformed input with std::expected
Real files get cut off by a full disk, mangled by a script, or saved in the wrong format. A parser should notice and say where, the way a compiler does: file:line: message. Return std::expected with an error that carries the line number. Here the read in bad.fq lost a quality character:
3 files, built together
#include <expected>
#include <format>
#include <fstream>
#include <print>
#include <string>
#include <vector>
struct Read {
std::string id;
std::string sequence;
std::string quality;
};
struct ParseError {
int line; // 0 when the problem is the file itself
std::string message;
};
std::expected<std::vector<Read>, ParseError>
read_fastq(const std::string& path) {
std::ifstream in(path);
if (!in) {
return std::unexpected(ParseError{0, "can't open the file"});
}
std::vector<Read> reads;
std::string header, sequence, plus, quality;
int line = 0;
while (std::getline(in, header)) {
int first = ++line;
if (!header.starts_with('@')) {
return std::unexpected(ParseError{first, "expected @ and a name"});
}
if (!std::getline(in, sequence) || !std::getline(in, plus) ||
!std::getline(in, quality)) {
return std::unexpected(ParseError{first, "read is cut short"});
}
line += 3;
if (quality.size() != sequence.size()) {
return std::unexpected(ParseError{
line, std::format("{} quality characters for {} bases",
quality.size(), sequence.size())});
}
reads.push_back({header.substr(1), sequence, quality});
}
return reads;
}
int main(int argc, char** argv) {
int failed = 0;
for (int i = 1; i < argc; ++i) {
auto reads = read_fastq(argv[i]);
if (reads) {
std::println("{}: {} reads", argv[i], reads->size());
} else {
const ParseError& e = reads.error();
std::string at = e.line > 0 ? std::format(":{}", e.line) : "";
std::println("{}{}: {}", argv[i], at, e.message);
++failed;
}
}
return failed == 0 ? 0 : 1;
}@read1
GATTACAGATTACA
+
IIIIIIIIIIII?5
@read2
ACGTTGCAACGT
+
IIIII???5+#!@read2
ACGTTGCAACGT
+
IIIII???5+#Build and run
g++ -std=c++23 -Wall -Wextra -Wpedantic main.cpp -o app ./app reads.fq bad.fq missing.fq
Output (exits with code 1)
reads.fq: 2 reads bad.fq:4: 11 quality characters for 12 bases missing.fq: can't open the file
- Each error names the line it’s about:
firstis the header’s line, and after all four lines are read,lineis the quality line’s.reads->size()callssize()on the vector inside thestd::expected. - The program reports every file, then exits with code 1 if any of them failed, so a script running it can tell. A command-line tool would normally print errors to standard error with
std::println(stderr, …)(Printing and reading); this one prints them with its results so you can see them here.
Common pitfallNever skip a bad read quietly
Dropping records you can’t parse hides a broken file: the results look fine but come from part of the data. Stop with an error, or count what you skipped and print the count.
Reading fast: one read, then views
std::getline copies every line into a std::string. That’s fine for most files, but a FASTQ file from one sequencing run can hold tens of gigabytes. A faster way is to load the whole file into one string with a single call, then point std::string_views into it instead of copying each line:
2 files, built together
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <print>
#include <string>
#include <string_view>
#include <vector>
struct ReadView {
std::string_view id;
std::string_view sequence;
std::string_view quality;
};
std::string read_file(const std::string& path) {
std::ifstream in(path, std::ios::binary);
std::string text(std::filesystem::file_size(path), '\0');
in.read(text.data(), static_cast<std::streamsize>(text.size()));
return text;
}
std::string_view next_line(std::string_view& text) {
std::size_t end = std::min(text.find('\n'), text.size());
std::string_view line = text.substr(0, end);
text.remove_prefix(std::min(end + 1, text.size()));
return line;
}
std::vector<ReadView> split_reads(std::string_view text) {
std::vector<ReadView> reads;
reads.reserve(std::ranges::count(text, '\n') / 4);
while (!text.empty()) {
std::string_view header = next_line(text);
std::string_view sequence = next_line(text);
next_line(text); // the + line
reads.push_back({header.substr(1), sequence, next_line(text)});
}
return reads;
}
int main() {
std::string text = read_file("reads.fq");
std::println("{} bytes", text.size());
for (const ReadView& r : split_reads(text)) {
std::println("{} {} starts at byte {}", r.id, r.sequence,
r.sequence.data() - text.data());
}
}@r1
ACGT
+
II5?
@r2
GGCATT
+
IIII#!Build and run
g++ -std=c++23 -Wall -Wextra -Wpedantic main.cpp -o app ./app
Output
36 bytes r1 ACGT starts at byte 4 r2 GGCATT starts at byte 20
std::filesystem::file_size(path)(from<filesystem>) gives the file’s size in bytes, sotextis allocated once at the right size.in.read(buffer, count)copies that many bytes into it in one call.std::ios::binaryreads the bytes exactly as they are, with no line-ending translation on Windows.next_linereturns a view of the text up to the next'\n', then movestextpast it withremove_prefix(n), which drops the firstncharacters from the view. Nothing is copied.reservemakes room for every read up front, counting four newlines per read: one allocation instead of a vector that grows step by step (vector).
Each view is a pointer into text and a length. r.sequence.data() - text.data() shows where it points: ACGT really is bytes 4 to 7 of the file’s text.
The views are valid only while text is alive and unchanged (see the first pitfall below). For brevity, this version skips the checks from the previous section; a real reader needs them too. How much faster it is than std::getline depends on your disk, your standard library and the file, so time both on your own data (Module 9 shows how) before switching. For files larger than your memory, read big blocks one at a time and carry a partial record from one block to the next.
Compressed files. Most FASTQ files are stored compressed with gzip, as reads.fq.gz. The standard library can’t read gzip. Either use a library (zlib’s gzopen and gzgets read a gzip file line by line; htslib reads FASTA, FASTQ and the binary alignment formats), or decompress in a pipe: zcat reads.fq.gz | ./app -, with the program reading std::cin when its argument is -. That’s one more reason to write parsers that take a std::istream&.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
std::getline loop | Most tools, and any file you read once from start to end. | Simple, works on any stream (std::cin, files, text in memory), and holds one record at a time. | while (std::getline(in, line)) { … } |
| Whole file + views | A file that fits in memory, when you’ve measured reading as the slow part. | One allocation and one read; records are views, with no copies. | in.read(text.data(), size), then std::string_views into text |
std::expected errors | Any parser of files a user hands you. | Bad input is expected, not exceptional; the caller decides whether to stop or skip, and the message names the line. | std::expected<std::vector<Read>, ParseError> |
Rule of thumb: start with a std::getline parser that takes a std::istream& and returns std::expected; switch to whole-file views only when a measurement says reading is the slow part.
Under the hood
std::ifstream doesn’t go to the disk for every line. It reads the file in blocks into a buffer of its own and hands out characters from there. std::getline then copies one line into your string, and it reuses the string’s heap block: once line has grown to fit the longest line, reading more lines allocates nothing. That’s why reading into the same std::string in a loop is cheap, and creating a new string for every line is not. A std::vector<ReadView> goes further: three pointer-and-length pairs per read and no characters at all.
Common pitfalls
Views into a string that’s gone
A function that loads the text into a local string and returns views into it hands back views of freed memory. It compiles without a warning; AddressSanitizer catches it on the first read:
#include <print>
#include <string>
#include <string_view>
#include <vector>
std::vector<std::string_view> load_ids() {
std::string text = "@read1 lane 1\n@read2 lane 1\n";
std::string_view all = text;
return {all.substr(1, 5), all.substr(15, 5)};
} // text is destroyed here
int main() {
std::vector<std::string_view> ids = load_ids();
std::println("{}", ids[0]);
}This fails when it runs
ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 5 at 0x… thread T0
#0 memcpy
… 9 frames inside the standard library
#10 main main.cpp:14
0x… is located 1 bytes inside of 29-byte region [0x…,0x…)
freed by thread T0 here:
#0 operator delete(void*, unsigned long)
… 6 frames inside the standard library
#7 load_ids() main.cpp:10
#8 main main.cpp:13
previously allocated by thread T0 here:
#0 operator new(unsigned long)
… 7 frames inside the standard library
#8 load_ids() main.cpp:7
#9 main main.cpp:13
SUMMARY: AddressSanitizer: heap-use-after-free main.cpp:14 in mainKeep the owner alive as long as its views: return the text and the views together in one struct, or have the caller own the text and pass it in, as split_reads(text) does above.
Two text traps
- A quality line can start with
@.@is Phred+33 for Q31. A parser that treats every line starting with@as a new read splits reads in the wrong places. Count lines instead: the header is every fourth line, as inread_fastq. - Windows line endings. A file saved on Windows ends each line with
"\r\n".std::getlinestops at'\n'and keeps the'\r', so every sequence gains a character and the quality-length check fails on every read. If your tool may get such files, remove a trailing'\r'after eachstd::getline:if (line.ends_with('\r')) { line.pop_back(); }.
Try it yourself
Try it yourself
Convert FASTQ to FASTA, keeping only reads with a mean quality of at least Q20. Read the records from text in memory with a std::istringstream (from <sstream>), a stream that reads from a string: std::istringstream in("@read1\nGATTACA\n+\nIIIII?5\n…");. Any function that takes a std::istream& accepts one, which makes it handy for tests.
Expected output
>read1 GATTACA >read2 ACGTAC
Show a hint
Read four lines per record with std::getline, as read_fastq does, compute the mean of c - 33 over the quality line, and print > and the name, then the bases, only when the mean is at least 20.
Show a solution
#include <print>
#include <sstream>
#include <string>
#include <string_view>
double mean_quality(std::string_view quality) {
int total = 0;
for (char c : quality) {
total += c - 33;
}
return static_cast<double>(total) / static_cast<double>(quality.size());
}
int main() {
std::istringstream in("@read1\nGATTACA\n+\nIIIII?5\n"
"@read2\nACGTAC\n+\nIIII\"!\n"
"@read3\nTTGG\n+\n++++\n");
std::string header, sequence, plus, quality;
while (std::getline(in, header) && std::getline(in, sequence) &&
std::getline(in, plus) && std::getline(in, quality)) {
if (mean_quality(quality) >= 20.0) {
std::println(">{}\n{}", header.substr(1), sequence);
}
}
}FASTA has no quality line, so converting means writing the name after > instead of @ and dropping the + and quality lines. read2's mean is (40·4 + 1 + 0) / 6 = 26.8 and read3's is 10, so only read1 and read2 are kept.
Saved in this browser only.