Arrays 2 - CENG114

Download Report

Transcript Arrays 2 - CENG114

Array & Functions
Reading From a File
FILE Operations
• FILE pointer declarations
– FILE *flptr;
• Open a file
– flptr = fopen(“filename”, “r”);
– “r” for read only, “w” for writing
• Read from a file – same as scanf
– fscanf(flptr, “%d%f %c”, &a, &b, &c);
• Write to a file – same as printf
– fprintf(flptr, “This is output %8.2f\n”, w);
• Close a file
– fclose(flptr);
Example
• Read grades from a file, find minimum,
maximum, and average
• fscanf returns EOF when it reaches the end of
file.
i=0;
do {
Status = fscanf(flptr, “%f”, &grd[i]);
i++;
} while(Status != EOF);
Example - Main
#include <stdio.h>
#define CLSZ 100
printf("The Maximum is: %3d\n", Max);
printf("The Minimum is: %3d\n", Min);
printf("The Average is: %6.2f\n", Ave);
int
FillArr(FILE *flp, int gr[]);
int
FindMax(int gr[], int sz);
int
FindMin(int gr[], int sz);
double FindAve(int gr[], int sz);
int main(void) {
FILE *flptr;
int Grd[CLSZ], SZ;
int Min, Max;
double Ave;
flptr = fopen("Grades.txt", "r");
SZ = FillArr(flptr, Grd);
Max = FindMax(Grd, SZ);
Min = FindMin(Grd, SZ);
Ave = FindAve(Grd, SZ);
fclose(flptr);
return(0);
}
Example - Functions
int FillArr(FILE *flp, int gr[]) {
int Status, i=0;
Status = fscanf(flp, "%d", &gr[i]);
while(Status != EOF) {
i++;
Status = fscanf(flp, "%d", &gr[i]);
}
return(i);
int FindMin(int gr[], int sz) {
int i, min;
min = gr[0];
for(i=1; i<sz; i++)
if(gr[i] < min) min=gr[i];
return(min);
}
}
int FindMax(int gr[], int sz) {
int i, max;
double FindAve(int gr[], int sz) {
double ave = 0.0;
int i;
for(i=0; i<sz; i++) ave+=gr[i];
ave=ave/sz;
max = gr[0];
for(i=1; i<sz; i++)
if(gr[i] > max) max=gr[i];
return(ave);
return(max);
}
}