/* CSE 303, Spring 2009, Marty Stepp This program reads student data from a file in the following format: section, studentID, year (1=frosh 4=senior), credits section is a 1-letter string studentID is a 7-digit number year is an integer from 1 through 4 credits is an integer from 0 through 27 example of input: C 9087231 2 18 B 7843254 3 10 */ #include #include #include #include // Shifts the given pointer by the given number of bytes and returns it. void* shift(void* p, int bytes) { return (void*) (((char*) p) + bytes); } // A struct type for students that occupies only 32 bits (4 bytes). typedef struct Student { unsigned studentID : 20; // 5-digit number: 2^20 > 1m unsigned year : 2; // 1-4 unsigned credits : 5; // 0-27 unsigned section : 5; // A-Z } Student; int main(void) { int i; int num_students; // a block of memory that we'll use to store 6 students; // C can store anything in any memory if we cast the pointers // stud1 stud2 ... // 0 4 8 12 16 20 char blob[24]; // [ 4 ] [ 4 ] [ 4 ] [ 4 ] [ 4 ] [ 4 ] FILE* f = fopen("students.txt", "r"); fscanf(f, "%d\n", &num_students); for (i = 0; i < num_students; i++) { // read a student: C 9087231 2 18 Student* s; char section; int id; int year; int credits; fscanf(f, "%c %d %d %d\n", §ion, &id, &year, &credits); s = (Student*) shift(blob, i * sizeof(Student)); // store data into fields of struct (pack those bits!) s->section = section - 'A'; // A-Z --> 0-25 s->studentID = id; s->year = year - 1; // 1-4 --> 0-3 s->credits = credits; } fclose(f); // print info about all students for (i = 0; i < num_students; i++) { Student* s = (Student*) (blob + (i * sizeof(Student))); printf("Student %d: section %c, id #%d, year %d, credits %d\n", i, s->section + 'A', // 0-25 --> A-Z s->studentID, s->year + 1, // 0-3 --> 1-4 s->credits ); } return 0; }