Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- typedef struct Student{
- char* studentName; //Dyn. alloc. of stud. name
- long id; // ID Number
- float mark; // mark
- unsigned char subjectStatus;
- }Student;
- typedef struct University{
- Student* studentArr; // Dync. Alloc(Realloc) of students
- int numOfStudents; //num of students
- }University;
- void getStudents(University *ptr);
- unsigned char stringToBinary(unsigned char tmpSubjectStatus[]);
- void main()
- {
- printf("Please enter details of student: (a)");
- University uni;
- getStudents(&uni); //Send address of structure University, because we want to change it not make a local copy of it
- getch();
- }
- void getStudents(University *ptr)
- {
- FILE *op;
- char tmpStudentName[20];
- long tmpId;
- float tmpMark;
- char tmpSubjectStatus[6];
- ptr->numOfStudents = 0;
- if ((op = fopen("input.txt", "r")) == NULL)
- {
- printf("Failed to open file.");
- }
- ptr->studentArr = (Student*)malloc(sizeof(Student));
- if (ptr->studentArr == NULL){
- printf("Error: memory was not allocated.");
- exit(1);
- }
- while (fscanf(op, "%s %ld %f %s", tmpStudentName, &tmpId, &tmpMark, tmpSubjectStatus) != NULL)
- {
- ptr->numOfStudents++;
- ptr->studentArr = (Student*)realloc(ptr->studentArr, sizeof(Student) * ptr->numOfStudents); /*Additional code for Realloc fails - we didn't study!*/
- ptr->studentArr[ptr->numOfStudents - 1].studentName = (char*)malloc(sizeof(char)* strlen(tmpStudentName));
- if (!(ptr->studentArr[ptr->numOfStudents - 1].studentName)) //if we failed to allocate memory for studentName
- {
- while (ptr->numOfStudents > 0)
- {
- free(ptr->studentArr[ptr->numOfStudents - 1].studentName); //free student name
- ptr->numOfStudents--; // decrease numOfStudents by one
- }
- free(ptr->studentArr); //if all student names are free, we need to free the array
- printf("Student name was not allocated.");
- exit(1);
- }
- strcpy(ptr->studentArr[ptr->numOfStudents - 1].studentName, tmpStudentName);
- ptr->studentArr[ptr->numOfStudents - 1].id = tmpId;
- ptr->studentArr[ptr->numOfStudents - 1].mark = tmpMark;
- ptr->studentArr[ptr->numOfStudents - 1].subjectStatus = stringToBinary(tmpSubjectStatus); //atoi: from "11001"(string) to 11001(int),then casting to unsigned char
- }
- fclose(op);
- }
- unsigned char stringToBinary(char tmpSubjectStatus[])
- {
- int tmpInteger;
- int tmpBinary = 0; //convert tmpInteger into binary number
- unsigned char tmpBinaryCh;
- int i = 0;
- int mostRightbit = 16;
- tmpInteger = atoi(tmpSubjectStatus); //Convert from string to int
- while (i < 5){
- if (((16 >> i) & tmpInteger) != 0){
- tmpBinary += (16 >> i);
- }
- i++;
- }
- tmpBinaryCh = (unsigned char)tmpBinary;
- return tmpBinaryCh;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement