How should I “play” with all records?
How about 1 line of the file == 1 record?
Code needs 2 functions:
void lessons_write(FILE *destination, const lessons *source);
// return 1: success, EOF: end-of-file, 0: fail
int lessons_read(FILE *source, lessons *destination);
A key consideration: Input may not be formatted correctly and so calling code needs to know when something failed.
Consider comma separated values CSV.
void lessons_write(FILE *destination, const lessons *source) {
// Maybe add tests here to detect if the record is sane.
fprintf(destination, "%s, %s, %s, %d\n",
source->LessonName,
source->TeacherName,
source->TeacherLastName,
source->numberOfStudents);
}
int lessons_read(FILE *source, lessons *destination) {
// Use a buffer large enough for any reasonable input.
char buf[sizeof *destination * 2];
// Use fgets to read **1 line**
if (fgets(buf, sizeof buf, source) == NULL) {
return EOF;
}
// Use %n to detect end of scanning. It records the offset of the scan.
int n = 0;
sscanf(buf, " %29[^,], %19[^,], %19[^,], %d %n",
destination->LessonName,
destination->TeacherName,
destination->TeacherLastName,
&destination->numberOfStudents, &n);
// If scan did not complete or some junk at the end ...
if (n == 0 || buf[n] != '\0') {
return 0;
}
// Maybe add tests here to detect if the record is sane.
return 1;
}
Now armed with basics, consider more advanced issues:
Can a course name or teachers name contain a ','
or '\n'
as that will foal up the reading? Perhaps form a bool Lessons_Valid(const lessons *source)
test?
Can a course name or teachers name begin, contain or end with spaces? Or control characters?
What range is valid for # of students? Perhaps 0-9999.
How about long names?
A key to good record handling is the ability to detect garbage input.
give some examples of how should I put the new record to a static array when the user enters all information about the lesson?
How about some pseudo code to not take all the learning experience away?
open file to read, successful?
Set N as 10
lessons abc[N]
for up to N times
read record and return success
Was that the last (EOF)?
Was is a bad record (Error message)
else save it and increment read_count
close input
for read_count
print the record to stdout