
Patrick B. answered 05/18/21
Math and computer tutor/teacher
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STUDENT_NAME_LENGTH (50)
#define DEPARTMENT_NAME_LENGTH (20)
#define MAX_NUM_STUDENTS (1000)
typedef struct
{
char name[STUDENT_NAME_LENGTH];
int id;
char dept[DEPARTMENT_NAME_LENGTH];
double cgpa;
} student;
typedef student _TStudent;
typedef _TStudent * TStudent;
void Student_Parse(TStudent studentRec, char * studentRecBuff)
{
strcpy(studentRec->name,strtok(studentRecBuff,","));
studentRec->id = atoi(strtok(NULL,","));
strcpy(studentRec->dept,strtok(NULL,","));
studentRec->cgpa = atof(strtok(NULL,","));
printf(" incoming student rec parsed : name >%s< id = %d dept=>%s< gpa = %6.2f \n",studentRec->name,
studentRec->id,
studentRec->dept,
studentRec->cgpa);
}
typedef struct _TStudentDB
{
_TStudent students[MAX_NUM_STUDENTS];
int numStudents;
} *TStudentDB;
void ReadStudentFile(TStudentDB studentDB,char * filename)
{
char inbuff[255];
int iIndexPos=0;
studentDB->numStudents=0;
FILE * fptr = fopen(filename,"r");
if (fptr!=NULL)
{
while (!feof(fptr))
{
fgets(inbuff,255,fptr);
if (iIndexPos>=MAX_NUM_STUDENTS) { break; }
Student_Parse(&studentDB->students[iIndexPos++],inbuff);
if (feof(fptr)) { break; }
}
studentDB->numStudents=iIndexPos;
fclose(fptr);
}
else
{
studentDB->numStudents=0;
iIndexPos = -1;
}
}
void DumpStudentRecs(TStudentDB studentDB,char * strMsg)
{
int i;
int N = studentDB->numStudents;
_TStudent curStudentRec;
if (strMsg!=NULL)
{
printf("*************************************************\n");
printf(strMsg);
}
printf("\n************************************************************\n");
for (i=0; i<N; i++)
{
curStudentRec = studentDB->students[i];
printf(" student rec # %d of %d : name >%s< id = %d dept=>%s< gpa = %6.2f \n",(i+1),N,
curStudentRec.name,
curStudentRec.id,
curStudentRec.dept,
curStudentRec.cgpa);
}
}
int main()
{
struct _TStudentDB studentDB;
char filename[55]; strcpy(filename,"E:\\input.csv");
char strmsg[55];
ReadStudentFile(&studentDB,filename);
printf(" read %d student record(s) from file \n",studentDB.numStudents);
sprintf(strmsg,"STUDENT RECS READ FROM FILE %s",filename);
DumpStudentRecs(&studentDB,strmsg);
}
and the file....
>cat input.csv
Moinul Islam,21,Computer Science,3.98
Abu Hena,11,Finance,3.45
Patrick Baldwin,33,Engineering,3.25
Shannon Jones,55,Communications,3.25