My program should print the letter frequency and the sum of the numbers of an input file in another output file. The letter frequency works just fine. The problem is that the sum part is ignored by the compiler so it prints the letter frequency and the sum is 0. I have tried a few things out but I can't figure out where the problem is. Hope u can help :)
So here is the code :
#define MAX_FILE_NAME 100
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void text_analysis(FILE*,FILE*, int,int freq [] );
int main()
{
FILE *in, *out;
int frequency[26] = {};
char filename[MAX_FILE_NAME];
int a, sum = 0;
int ch = 0;
//Give the name of the file you want to open
printf("Enter file name: ");
scanf("%s", filename);
// Open the file in to read
in = fopen(filename, "r");
if (in == NULL)
{
printf("Could not open file %s",
filename);
return 0;
}
//Open the file out to write the output
out = fopen("output.txt", "w");
if (out == NULL)
{
printf("Cannot open destination file.\n");
exit(1);
}
do {
// read each character from input file
ch = fgetc(in);
//read all the numbers in the file and calculate the sum
if( isdigit( (char)ch ) )
{
ungetc( (char)ch, in );
if( fscanf( in, "%8d", &a ) != 1 )
{
fprintf( stderr, "fscanf for number failed\n" );
}
sum += a;
}
//Call the function to analyse the text and return the frequency of the letters in the file
text_analysis(in,out, ch, frequency);
}
while (!feof(in));
//Print the sum of the numbers in the file
fprintf(out, "\n The sum of all numbers in the file is: %d \n", sum);
//Close the files
fclose(out);
fclose(in);
return 0;
}
void text_analysis(FILE *in,FILE *out, int c, int freq[]) {
while ( (c = fgetc(in)) != EOF)
{
/** Considering characters from 'a' to 'z' only
and ignoring others */
if ('a' <= c && c <= 'z')
freq[c-'a']++;
else if('A' <= c && c <= 'Z')
freq[c-'A']++;
}
//Print the letters a-z and the frequency in the output file
fputs("character\t\t\t\tfrequency", out);
for (c = 0; c < 26; c++)
{
fprintf(out, "\n%c\t\t\t\t\t\t%2d", c+'a',freq[c]);
}
}