Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX 20
#define SIZE 5
//date structure
typedef struct
{
char month[MAX];
int date;
int year;
} DATE;
//student structure
typedef struct
{
char fName[MAX];
char lName[MAX];
int gLevel;
char sNumber[MAX];
DATE bDate;
} STUDENT;
//functions
void fill(STUDENT identity[], FILE* fpIn, FILE* fpOut);
void printArr(STUDENT identity[]);
bool openFiles(FILE **pFPIn, FILE **pFPOut);
void prt(STUDENT identity);
void sort(STUDENT identity[]);
void swap(STUDENT *pN1, STUDENT *pN2);
//main function
int main(int argc, char* argv[])
{
STUDENT identity[SIZE];
FILE *fPIn, *fPOut;
int i;
if (openFiles(&fPIn, &fPOut))
{
fill(identity, fPIn, fPOut);
printf("\nCreated by _______");
printf("\n\n%26s %10s %15s %17s", "Name", "Level",
"SSN", "Birthdate");
printf("\n%26s %10s %15s %17s", "----", "-----",
"---", "---------");
printArr(identity); //prints the unsorted array
sort(identity); //sorts the array
printArr(identity); //prints the sorted array
}
fclose(fPIn);
fclose(fPOut);
return 0;
}
//generate function
void fill(STUDENT identity[], FILE* fPIn, FILE* fPOut)
{
int i;
//for loop
for (i = 0; i < SIZE; i++)
{
fscanf(fPIn, "%s%s%d%s%s%d%d",
identity[i].fName, identity[i].lName,
&identity[i].gLevel, identity[i].sNumber,
&identity[i].bDate.month, &identity[i].bDate.date,
&identity[i].bDate.year);
}
}
//print function into array of structures
void printArr(STUDENT identity[])
{
int i;
//for loop
for (i = 0; i < SIZE; i++)
{
printf("\n");
prt(identity[i]);
}
printf("\n\n");
}
//opens the files
bool openFiles(FILE **pFPIn, FILE **pFPOut)
{
bool success = false;
if ((*pFPIn = fopen("t1", "r")) != NULL)
{
if ((*pFPOut = fopen("t1.out", "w")) != NULL)
success = true;
else
printf("\nUnable to open \"t1.out\" for writing.\n\n");
}
else
printf("\nUnable to open \"t1.txt\" for reading.\n\n");
return success;
}
//prints the function
void prt(STUDENT identity)
{
printf("%17s %8s %10d %15s %9s %2d %d%", identity.fName,
identity.lName,
identity.gLevel,
identity.sNumber,
identity.bDate.month,
identity.bDate.date,
identity.bDate.year);
}
//selection sort function
void sort(STUDENT identity[])
{
int pass, min, trav;
for (pass = 0; pass < SIZE - 1; pass++)
{
for (min = pass, trav = pass + 1; trav < SIZE; trav++)
{
if (identity[trav].lName < identity[min].lName)
{
min = trav;
}
trav++;
}
swap(&identity[pass], &identity[min]);
pass++;
}
}
//swap function
void swap(STUDENT *pN1, STUDENT *pN2)
{
char temp;
temp = pN1;
pN1 = pN2;
pN2 = temp;
}
The current swap function is the only way that I have done that would compile, it gave me warning messages however.