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.

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);
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.