I have written code to solve the following Rosalind problem. This is my first time writing in C and I would like a review of my code, particularly in regard to correctness and performance.
#include <stdio.h>
#include <string.h>
int main() {
/* Input DNA of length at most 1000 nucleotides */
char dna[1000];
FILE *input;
input = fopen("/Users/James/Desktop/rosalind_dna.txt", "r");
fgets(dna, 1000, input);
fclose(input);
/* Count frequency of symbols 'A', 'C', 'G' and 'T' in DNA */
int i, a, c, g, t;
for(i=0; i<strlen(dna); i++) {
if (dna[i] == 'A') {
a += 1;
}
else if (dna[i] == 'C') {
c += 1;
}
else if (dna[i] == 'G') {
g += 1;
}
else if (dna[i] == 'T') {
t += 1;
}
}
/* Output frequency of DNA nucleotides */
printf("%i %i %i %i", a, c, g, t);
return 0;
}
Updated Code
#include <stdio.h>
#include <string.h>
#define READ_BUFFER_SIZE 1000
int main() {
/* Input DNA of length at most 1000 nucleotides */
char dna[READ_BUFFER_SIZE];
FILE *input;
input = fopen("/Users/James/Desktop/rosalind_dna.txt", "r");
if (input == NULL) {
perror("Error");
}
fgets(dna, READ_BUFFER_SIZE, input);
fclose(input);
/* Count frequency of symbols 'A', 'C', 'G' and 'T' in DNA */
int aCount, cCount, gCount, tCount;
char *current;
for(current = dna; *current; ++current) {
switch(*current){
case 'A':
++aCount;
break;
case 'C':
++cCount;
break;
case 'G':
++gCount;
break;
case 'T':
++tCount;
break;
default:
printf("Error: Invalid nucleotide\n");
break;
}
}
/* Output frequency of DNA nucleotides */
printf("%i %i %i %i", aCount, cCount, gCount, tCount);
return 0;
}