-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathfastq2fasta.cpp
111 lines (97 loc) · 2.12 KB
/
fastq2fasta.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// convert a fastq file to fasta
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <getopt.h>
using namespace std;
void helpme() {
fprintf(stderr,
"fastq2fasta [options] <fastq file> <fasta file>\n"
"Options:\n"
"\t-r replace spaces in the fasta header line with '_'\n"
"\t-n <1/2> add the read number to the header line at the first space\n"
);
}
int main (int argc, char* argv[]) {
if ( argc < 3) {
helpme();
return 1;
}
int replace = 0;
string n;
for (;;) {
switch(getopt(argc, argv, "rn:")) {
default:
helpme();
return 1;
case -1:
break;
case 'r':
replace = 1;
continue;
case 'n':
n = optarg;
continue;
}
break;
}
if (optind +2 != argc) {
helpme();
return 1;
}
char* fqf = argv[optind];
char* faf = argv[optind+1];
ifstream fastq;
// streambuf* orig_cin = 0;
if (strcmp(fqf, "-") != 0) {
cout << "reading from " << fqf << '\n';
fastq.open(fqf);
if (!fastq) return 1;
// orig_cin = cin.rdbuf(fastq.rdbuf());
cin.rdbuf(fastq.rdbuf());
cin.tie(0); // tied to cout by default
}
string line;
ofstream fasta(faf);
if (!fasta) return 2;
int c=0;
while (getline(cin, line))
{
//cout << c << " : " << line << '\n';
if ( c==0 ) {
line.replace(0, 1, ">");
if (replace) {
for (long unsigned int i = 0; i <= line.length(); i++) {
if (line[i] == ' ') {
line[i] = '_';
}
}
}
else if (n.size()) {
int changed = 0;
for (long unsigned int i = 0; i <= line.length(); i++) {
if (line[i] == ' ') {
line.insert(i++, string("/") + n);
changed = 1;
break;
}
}
if (changed == 0) {
line += string("/") + n;
}
}
fasta << line << '\n';
}
if ( c==1 ) {
fasta << line << '\n';
}
c++;
if ( c == 4) { c=0 ;}
}
if ( c != 0 ) {
cerr << "ERROR: There appears to be the wrong number of lines in your file!" << endl;
return 1;
}
return 0;
}