Hi,
I'm still fairly new at C and have been asked to build a program that will count a number of specified letters to be read from a text file. This is the second stage of the task, the first being to write a program that reads a text file, removes all the spaces and converts the message to upper case, saving it in a new output text file.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void main()
{
FILE *fpin, *fpout, *fprec; // declares two file streams, in and out
int tl, f, i=0;
int nl=0;
char ch, let=0; // ch is variable to be used in conversion
char input[80], output[80], record[80]; // declared arrays to store file paths
printf("Input input file name: \n");
gets(input); // input file location
printf("Input output file name: \n");
gets(output); // output file location
printf("Input record file name: \n");
gets(record); // record file location
if((fpin = fopen(input,"r")) == NULL) // confirms that file has been opened
{
printf("Unable to open input file");
exit(0);
}
if((fpout = fopen(output,"w")) == NULL) // confirms that file has been created
{
printf("Unable to open output file\n");
exit(0);
}
tl=0;
while((ch=getc(fpin))!=EOF) // read input file until the end of the file
{
if((ch>='a' && ch<='z') | (ch>='A' && ch<='Z')) // ensures that only alphabetic characters are transferred
{
putc(toupper(ch), fpout); //function to change all the characters to upper case
tl++;
}
}
fclose(fpin); // close input file
fclose(fpout);
fopen(output,"r");
if((fprec = fopen(record,"w")) == NULL) // confirms that file has been created
{
printf("Unable to open record file\n");
exit(0);
}
printf("Total number of letters in the file: %d\n", tl);
printf("Which letter would you like the frequency of?\n");
scanf("%c", let);
This is the area I am having difficulty with. My thinking is that if I can get ch into normal string format I will be able to use a for loop to go through each character and determine whether or not it is the character that the user has input.
Code:
while((ch=getc(fpout))!=EOF) // read input file until the end of the file
{
char c = tolower(ch);
if(let=c)
{
nl++;
}
}
f=(nl/tl)*100;
printf("%d", f);
putc(f, fprec);
fclose(fpout);
fclose(fprec);
}
Unfortunately however, I either don't know how to do this, or as a result of having spent the last 6 hours banging my head on this thing I have simpley forgotten. If anyone can fill me in or see a more logical way of doing this I'm open to all suggestions.
Thanks for your time.
James