Ali Folks
Ali Folks

Reputation: 11

read char from file

I would like to know why my program gets wrong result. I just need to read characters from file including white space, (.), (,), and others and output them in particular string format. As a result I get more 300 instances of char read and their weird representation.I need to print the actual character and it's memory location. Appreciate it!

 34 instances of character :
 35 instances of character ¼
 36 instances of character ¼
 37 instances of character ¼

  #include <stdio.h>

  int main()
  {
   char ch;
   int characters[100];
   int i,j,k;
   int charCount = 0;

   FILE *fPtr;
   fPtr=fopen("input.txt", "r");

   while(ch = fgetc(fPtr) != EOF)
   {
     i=0;
     characters[i] = (char)ch;
     i++;
   }

   int arrayLength = sizeof(characters)/sizeof(characters[0]);

   for(j= 0; j < arrayLength; j++)
   {
     for(k=1; k < arrayLength; k++)
     {
       if(characters[j] == characters[k])
   {
      charCount++;
          printf("%d instances of character %c in location %c \n", charCount, characters[j], &characters[j]);
   }
     }
   }
 }

Upvotes: 0

Views: 8152

Answers (1)

unwind
unwind

Reputation: 399833

Remember this: fgetch() returns int. Not char. See the man page.

This is because the EOF constant is larger than a character, so there has to be more bits in the return value to be able to express "any character, or EOF".

In other words, EOF is not a character, it's an example of out-of-band communications.

Also, your parenthesis look odd, you probably mean:

while((ch = fgetc(fPtr)) != EOF && ch != '\n')

Note inner parenthesis around the assignment, only.

Upvotes: 1

Related Questions