This sample program reads data from a file line-by-line and if whenever it finds students who got a 5, it will write it to a second file.
The format for the input file: <name> <grade>
1 2 3 4 5 6 7 |
Marju 4 Olga 5 Toomas 3 Helen 2 Peeter 5 Albert 4 Madis 5 |
Notice the following:
- The second file is not opened before we make sure that the first one opened successfully
- If opening the output file fails, first the input file is closed and only then we exit the program.
- Notice that this program is also susceptible to buffer overflow attacks (not the scope for this sample).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
/** * File: grades.c * Author: Risto Heinsar * Created: 12.02.2015 * Modified: 12.08.2024 * * Description: Sample code using multiple file pointers at the same time. * It finds the students who got 5 as the grade for the subject * and outputs it to another file. */ #include <stdio.h> #include <stdlib.h> /* Names of files */ #define F_INPUT "grades.txt" #define F_OUTPUT "fivers.txt" /* Exit failure codes */ #define EXIT_INPUT_FAIL -1 #define EXIT_OUTPUT_FAIL -2 /* Name buffer length */ #define NAME_LEN 128 int main(void) { /* Declare file pointer and attempt to open a file */ FILE *fi = fopen(F_INPUT, "r"); /* Check if it was opened successfully */ if (fi == NULL) { printf("Error opening input file \"%s\"\n", F_INPUT); exit(EXIT_INPUT_FAIL); } /* Open and check for output file */ FILE *fo = fopen(F_OUTPUT, "w"); if (fo == NULL) { printf("Error opening output file\"%s\"\n", F_OUTPUT); /* Since fi was opened, we need to close it before exit */ fclose(fi); exit(EXIT_OUTPUT_FAIL); } int grade; char name[NAME_LEN]; /* Read the names and grades */ while (fscanf(fi, "%s %d", name, &grade) == 2) { if (grade == 5) { fprintf(fo, "%s %d\n", name, grade); } } /* Close the files before exiting */ fclose(fi); fclose(fo); return EXIT_SUCCESS; } |