60 likes | 189 Vues
This guide explores file operations in C, demonstrating how to open, read, write, and close files using standard libraries. We cover the use of file pointers, opening files in read and write modes, and utilizing functions like `fscanf()` for reading and `fprintf()` for writing. An example is provided that reads grades from a file, calculates the minimum, maximum, and average grades, and outputs the results to the console. Key functions include `FillArr()`, `FindMax()`, `FindMin()`, and `FindAve()` for processing the data efficiently.
E N D
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 • intFillArr(FILE *flp, intgr[]); • intFindMax(intgr[], intsz); • intFindMin(intgr[], intsz); • double FindAve(intgr[], intsz); • int main(void) { • FILE *flptr; • intGrd[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); • printf("The Maximum is: %3d\n", Max); • printf("The Minimum is: %3d\n", Min); • printf("The Average is: %6.2f\n", Ave); • fclose(flptr); • return(0); • }
Example - Functions • intFindMin(intgr[], intsz) { • inti, min; • min = gr[0]; • for(i=1; i<sz; i++) • if(gr[i] < min) min=gr[i]; • return(min); • } • double FindAve(intgr[], intsz) { • double ave = 0.0; • inti; • for(i=0; i<sz; i++) ave+=gr[i]; • ave=ave/sz; • return(ave); • } • intFillArr(FILE *flp, intgr[]) { • int Status, i=0; • Status = fscanf(flp, "%d", &gr[i]); • while(Status != EOF) { • i++; • Status = fscanf(flp, "%d", &gr[i]); • } • return(i); • } • intFindMax(intgr[], intsz) { • inti, max; • max = gr[0]; • for(i=1; i<sz; i++) • if(gr[i] > max) max=gr[i]; • return(max); • }