Code:
/*
* A sample program to read-from and write-to files. Also shows how to
* send a file as a parameter and display error messages to standard
* error.
*/
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main () {
STUDENT stuArr[MAX_STUDENTS];
void rmNl ( char s[] );
void *fin, *fout;
void grades_in(FILE *fin, FILE *fout, STUDENT stuArr[MAX_STUDENTS]);
/* Open file to read input data */
if ( ( fin = fopen ( "grades.in", "r" ) ) == NULL ) {
fprintf ( stderr, "Could not open file grades.in\n" );
exit ( -1 );
}
/* Open file for writing output */
if ( ( fout = fopen ( "grades.out", "w" ) ) == NULL ) {
fprintf ( stderr, "Could not open file grades.out\n" );
fclose ( fin );
exit ( -1 );
}
grades_in(fin, fout, stuArr);
system ("PAUSE");
return 0;
}
void grades_in(FILE *fin, FILE *fout, STUDENT stuArr[MAX_STUDENTS]) {
int numItems = 0;
char buf[MAX_STUDENTS];
char fname[50], lname[50];
int h1, h2, h3, h4, h5, e1, e2, e3, id;
while( fgets ( buf, MAX_STUDENTS, fin ) != NULL ) {
rmNl ( buf );
if ( !lineWithBlanks ( buf ) )
if ( sscanf(buf, "%s %s", fname, lname) == 2 ) printf ("%s %s\n", fname, lname);
if ( sscanf(buf, "%d", &id) == 1 ) printf ("%d\n", id);
if ( sscanf(buf, "%d %d %d %d %d", &h1, &h2, &h3, &h4, &h5) == 5 ) printf ("%d %d %d %d %d\n", h1, h2, h3, h4, h5);
if ( sscanf(buf, "%d %d %d", &e1, &e2, &e3) == 3 ) printf ("%d %d %d\n", e1, e2, e3);
numItems++;
continue;
}
}
/*
* Function to remove new line character
*/
void rmNl ( char str[] )
{
char *ptr;
if ( ( ptr = strchr ( str, '\n' ) ) )
*ptr = '\0';
}
/*
* Check to see if line is an empty one with only spaces
* Returns 1 if line consists of blank spaces, 0 otherwise
*/
int lineWithBlanks ( char *s )
{
int result = 1, i;
for ( i = 0; i < strlen (s); i++ ) {
if ( s[i] != ' ' ) {
result = 0;
break;
}
}
return result;
}