// The idea of the homework is to write a program which contains a function which creates a .txt file and 
// another separate function which opens an already existing .txt file which should have in itself 
// Student's name, average grade and Faculty Number and 
// a third function which reads from this file (with the info about the students) and 
// prints it out on the screen or something like that and last but not least a function that calculates the average of all students.
// If you give some basic code, even pseudo, or post some tutorials, close to my problem I'd be very very thankful. Thanks in advance (:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void createText(char *infile) {
  FILE *infil = fopen(infile, "a");
  if (infil != NULL) {
  char line[301];
  int i=1;
  line[0] = 'a';
  while (line[0] >= 32) {
    printf("Enter record %d consisting of Student's Name,Average Grade,Faculty Number (please include the commas, <cr> exits): ", i);
    line[0] = 0;
    if (fgets(line, 300, stdin) != NULL) {
     if (line[0] >= 32) {
      fprintf(infil, "%s", line);
      i++;
     }
    } 
  }
  fclose(infil);
  }
}

void readText(char *infile) {
  FILE *infil = fopen(infile, "r");
  char line[301] = " \0", *pch, fmt[10] = "%34s\t\t";
  int i=1;
  while (line[0] >= 32) {
    if (fgets(line, 300, infil) != NULL) {
      if (line[0] >= 32) {
        if (i == 1) printf("                    Student's Name\t\t Average Grade\t\tFaculty Number\n\n");
  		pch = strtok (line, ",");
  		while (pch != NULL)
  		{
    	    printf(fmt, pch);
    	    strcpy(fmt, "%14s\t\t");
    		pch = strtok (NULL, ",");
  		}
    	strcpy(fmt, "%34s\t\t");
        printf("\n");
      }
      i++;
    } else {
      line[0] = 0;
    }
  }
  fclose(infil);
}

void readAverageGrade(char *infile) {
  FILE *infil = fopen(infile, "r");
  char line[301] = " \0", *pch;
  double avgrad = 0.0, tavgrad;
  int i=1, ipos=0;
  while (line[0] >= 32) {
    if (fgets(line, 300, infil) != NULL) {
      if (line[0] >= 32) {
  		pch = strtok (line, ",");
  		ipos = 1;
  		while (pch != NULL)
  		{
    		pch = strtok (NULL, ",");
    		if (ipos == 1) sscanf(pch, "%lf", &tavgrad);
    		ipos++;
  		}
        avgrad = (avgrad * ((double)(i - 1)) + tavgrad) / (double)i;    
      }
      i++;
    } else {
      line[0] = 0;
    }
  }
  fclose(infil);
  printf("\n\nAverage Grade is %lf\n", avgrad);
}

int main() {
      char inname[301];
      printf("Enter name for student file: ");
      fgets(inname, 300, stdin); 
      sscanf(inname, "%[^\n]s", inname); 
      createText(inname);
      readText(inname);
      readAverageGrade(inname);
      return 0;
}