0

I need to write a function that opens a DAT file and calculates the average number of characters per line. Heres what I have so far...

# include <stdio.h>

int main (void)
{
  FILE *fp;
  int i;
  int counter;
  char ch;

  fp =fopen("TEST.DAT", "r");

  for (i = 1; i < EOF; i++)
  {
    while ((ch = fgetc(fp)) != EOL)
    {
      if (ch == ' ')
      {
        counter = counter;
      }
      else
      {
        counter = counter +1;
      }
      
      
    }
  }
  
  return(0);
}

Any help would be greatly appreciated.

2
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by Chainsaw
0

This is a revision of the code I have

# include <stdio.h>

int main (void)
{
  FILE *fp;
  int i;
  int counter;
  int results;
  char ch;


  fp =fopen("TEST.DAT", "r");

  for (i = 1; i < EOF; i++)
  {
    while ((ch = fgetc(fp)) != '/n')
    {
      if (ch == ' ')
      {
        counter = counter;
      }
      else
      {
        counter = counter +1;
      }

      results = counter / i;
    }
  }

  fclose(fp);

  fp = fopen("results.DAT", "w");

  fprintf(fp, "%d", results);

  fclose(fp);

  return(0);
}
0

Close, but you want to count the number of LINES, and the total number of BYTES you read. How about this pseudocode for the loop:

int ch; // fgetc returns an int, not a char
// skip the for loop, that wasn't buying you much
while ((ch = fgetc(fp)) != EOF)  // while we aren't at the END of the file
{
    if (ch == '\n')
        totalLines++;    // one more line read
    else  
        totalChars++;   // one more char read (assuming you don't count \n as a char)
}

And then the result would be totalChars/totalLines, and you should make sure totalLines is not zero or else the division will fail.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.