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

struct Student{
	unsigned id;
	char name[50];
	char faculty[50];
	float rating;
};

struct Student *
allocate_array(int n){
	struct Student *students = NULL;
	students = malloc(sizeof(struct Student)*n);

	if(!students)
		exit(1);

	return students;
}

void
fill_array(int n, struct Student *students)
{
	for(int i = 0; i < n; i++){
		printf("\nEnter student's № %d info:\n", i);

		printf("\tid:");
		scanf("%u", &students[i].id);
		getchar();

		printf("\tname:");
		fgets(students[i].name, sizeof(students[i].name), stdin);
		students[i].name[strcspn(students[i].name, "\n")] = 0; 

		printf("\tfaculty:");
		fgets(students[i].faculty, sizeof(students[i].faculty), stdin);
		students[i].faculty[strcspn(students[i].faculty, "\n")] = 0; 

		printf("\trating:");
		scanf("%f", &students[i].rating);
		getchar();
	}
}

void
write_array(FILE *file, int n, struct Student *students)
{
	for(int i = 0; i < n; i++){
		fprintf(file, "%u,%s,%s,%f\n", students[i].id, students[i].name, students[i].faculty, students[i].rating);
	}
}

void
bin_write_array(FILE *file, int n, struct Student *students)
{
	fwrite(&students[0], sizeof(struct Student), n, file);
}

struct Student*
bin_read_file_to_array(FILE *file, int n)
{
	struct Student *students = allocate_array(n);
	fread(students, sizeof(struct Student), n, file);
	return students;
}

struct Student *
read_file_to_array( FILE *file, int n)
{
	char *buf = NULL;
	buf = malloc(255);
	struct Student *students = allocate_array(n);	

	if(!buf)
		exit(1);

	char *tmp;

	int i = 0;
	while(fgets(buf, sizeof(struct Student), file) != NULL && i != n){
		if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n'))
			buf[strlen (buf) - 1] = '\0';

		tmp = strtok(buf, ",");
		students[i].id = atoi(tmp);

		tmp = strtok(NULL, ",");
		strcpy(students[i].name, tmp);

		tmp = strtok(NULL, ",");
		strcpy(students[i].faculty, tmp);

		tmp = strtok(NULL, ",");
		students[i].rating = atof(tmp);
		i++;
	}
	free(buf);
	return students;
}

void
print_array(int n, struct Student *students)
{
	for(int i = 0; i < n; i++){
		printf("Student №%d\n\tid:%u\n\tname:%s\n\tfaculty:%s\n\trating:%f\n", i, students[i].id, students[i].name, students[i].faculty, students[i].rating);
	}
}
