Hi all.
Here is my program to open a text file and to count the instances of each character. The output shows the correct information, but also displays extra information for which I can't explain.
What is =1 at the bottom of the output? Sometimes it(or another number) appears twice half way through the output, instead of at the bottom. Thank you.
Code:
// charactercount.c: Count the number of instances of each character in a text file.
#include <stdio.h>
#include <stdlib.h>
#define MAX_FILENAME_LENGTH 30
struct Character // structure to contain character, and the number of instances of character
{
char ch;
int counter; //number of instances of ch
};
int main(void)
{
struct Character list[256]; // ascii character set
int count, ch;
char filename[MAX_FILENAME_LENGTH];
FILE *openfile;
puts("Enter file to open");
fgets(filename, MAX_FILENAME_LENGTH, stdin);
filename[strlen(filename) - 1] = '\0';
if((openfile = fopen(filename, "r")) != NULL)
printf("File opened successfully\n\n");
else
{
perror("Error");
exit(1);
}
for(count = 0; count < 256; count++) // initialise ch and counter to 0
{
list[count].ch = 48; // 48 is ascii code for character 0
list[count].counter = 0;
}
while((ch = fgetc(openfile)) != EOF)
{
for(count = 0; count < 256; count++) // compare ch to values in array, if it already exists
if(ch == list[count].ch) // then increment it's counter
{
list[count].counter++;
break;
}
else
{ // if ch does not exist(because it's counter is 0), then assign
if(list[count].counter == 0) // it to the array and increment it's counter
{
list[count].ch = ch;
list[count].counter++;
break;
}
}
}
for(count = 0; count < 256; count++) // print values of structures that have a character stored
{
if(list[count].counter != 0)
printf("%c = %d\n", list[count].ch, list[count].counter);
else
break;
}
fclose(openfile);
return 0;
}
Sample output:
Code:
Enter file to open
test1.txt
File opened successfully
e = 6
m = 1
a = 4
i = 7
l = 3
= 8
n = 3
o = 3
t = 3
f = 1
c = 2
r = 2
v = 1
d = 2
: = 1
b = 3
u = 1
y = 3
w = 1
p = 2
k = 1
s = 1
= 1