Confused on fgets with switch
Hi,
I'm currently taking a class at my local college and the assignment is for me to retrieve data from a text file and count the number of 'a's, 'c's, 'g's, and 't's in the text file. When I run my code, it only counts the number of 'a's in the switch and I have no idea why. Could someone kindly look over my code and point out where I have erred? I have spent several hours trying to figure this out by myself, and really don't understand what I'm doing incorrectly :( !
Code:
/*
============================================================================
Name : xxx xxx xxx
Author : xxx xxx xxx
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* required to run strcat, which adds text to the end of a string */
#include <dirent.h> /* library for showing all files in a directory */
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
unsigned int a=0,c=0,g=0,t=0;
char filename[BUFSIZ],savename[BUFSIZ],stringCH[BUFSIZ];
FILE *pInFile,*pOutFile;
/* LISTS ALL FILES IN DIRECTORY */
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
printf("Here are the files in this directory:\n");
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
/* INPUT READ FILE FROM USER */
printf("\nPlease type the name of a TEXT file to read from, without the extension:\n");
fgets(filename, BUFSIZ, stdin); /* user inputs file to load */
strtok(filename,"\n"); /* removes the \n from fgets */
strcat(filename,".txt"); /* adds .txt to the string */
if((pInFile=fopen(filename,"r"))==0)
{
printf("You entered %s which is invalid. You must enter a proper TEXT file! Goodbye!\n",filename);
fclose(pInFile);
exit(0);
}
/* INPUT WRITE FILE FROM USER */
printf("Excellent! Now create a name of a TEXT file to write to, without an extension:\n");
fgets(savename, BUFSIZ, stdin); /* user inputs file to load */
strtok(savename,"\n"); /* removes the \n from fgets */
strcat(savename,".txt"); /* adds .txt to the string */
pOutFile=fopen(savename,"w");
/* EXECUTION OF DATA RETREVIAL */
printf("Great! Retrieving data from the READ file:\n\n");
while(fgets(stringCH,BUFSIZ,pInFile)!=NULL)
{
switch(stringCH[1])
{
case 'a':
++a;
break;
case 'c':
++c;
break;
case 'g':
++g;
break;
case 't':
++t;
break;
default:
printf("There was no data to read from!");
break;
} //--> END OF SWITCH
} //--> END OF WHILE LOOP
if(feof(pInFile)) //--> AFTER END OF WHILE LOOP/CHECKS FOR END-OF-FILE TRUE
{
printf("Results are as follows:\n");
printf("A\tC\tG\tT\n");
printf("%d\t%d\t%d\t%d\t\n",a,c,g,t);
fprintf(pOutFile,"%d %d %d %d",a,c,g,t);
fclose(pInFile);
fclose(pOutFile);
}
else if(ferror(pInFile)) //--> IF ERROR READING FILE, GOODBYE!
{
printf("Error reading from file. Goodbye!\n");
fclose(pInFile);
fclose(pOutFile);
exit(0);
}
return EXIT_SUCCESS;
} //--> END OF MAIN