C Exercise Example100
# C Programming Exercise - Example 100: Student Record Management and File I/O
This tutorial is part of the classic **C 100 Examples** series. In this exercise, you will learn how to manage structured data using C structures (`struct`), perform basic arithmetic calculations, and persist the processed data to a physical disk file using C's standard File I/O library.
---
## 1. Problem Description
Write a C program that processes academic records for five students.
* **Input:** For each student, read their ID, Name, and scores for three courses (Math, English, and C Programming) from the keyboard.
* **Processing:** Calculate the average score for each student.
* **Output:** Save the original student details along with their calculated average scores into a local disk file named `"stud"`.
---
## 2. Program Analysis & Concepts
To solve this problem efficiently, we will use several core C programming concepts:
### Structs (Structures)
A `struct` allows us to group variables of different data types under a single name. This is ideal for representing a "Student" entity, which contains integers (ID, grades) and a character array (Name).
```c
typedef struct {
int ID;
int math;
int English;
int C;
int avargrade;
char name;
} Stu;
```
### File I/O in C
We will use the standard `` library functions to handle file operations:
* `fopen()`: Opens a file stream. We use the `"w"` (write) mode to create a new file or overwrite an existing one.
* `fprintf()`: Writes formatted data to the file stream, similar to how `printf()` writes to the console.
* `fclose()`: Closes the file stream to flush buffers and release system resources.
---
## 3. Source Code Implementation
Below is the complete, clean C program. Copy this code into your IDE or text editor to run it.
```c
/**
* File: main.c
* Description: Read 5 students' information, calculate their average grades,
* and save the records to a disk file named "stud".
*/
#include
#include
// Define a structure to represent student records
typedef struct {
int ID;
int math;
int English;
int C;
int avargrade;
char name;
} Stu;
int main()
{
FILE *fp;
Stu stu;
int i;
printf("Please enter information for 5 students (ID, Name, 3 Grades):\n");
// 1. Read student data from standard input and calculate averages
for (i = 0; i < 5; i++)
{
// Input format:
scanf("%d %s %d %d %d",
&(stu.ID),
stu.name,
&(stu.math),
&(stu.English),
&(stu.C));
// Calculate the average grade (integer division)
stu.avargrade = (stu.math + stu.English + stu.C) / 3;
}
// 2. Open the destination file "stud" for writing
if ((fp = fopen("stud", "w")) == NULL)
{
printf("Error: Cannot open or create the file!\n");
exit(1);
}
// 3. Write the structured data to the file
for (i = 0; i < 5; i++)
{
fprintf(fp, "%d %s %d %d %d %d\n",
stu.ID,
stu.name,
stu.math,
stu.English,
stu.C,
stu.avargrade);
}
// 4. Close the file stream
fclose(fp);
printf("\nData successfully saved to file 'stud'.\n");
return 0;
}
```
---
## 4. Execution and Output
### Step 1: Console Input
When you run the program, enter the data for 5 students as prompted:
```text
Please enter information for 5 students (ID, Name, 3 Grades):
1 a 60 70 80
2 b 60 80 90
3 c 59 39 89
4 e 56 88 98
5 d 43 88 78
```
### Step 2: File Output Verification
After execution, a file named `stud` will be created in the same directory as your executable. Open the `stud` file with any text editor to verify its contents:
```text
1 a 60 70 80 70
2 b 60 80 90 76
3 c 59 39 89 62
4 e 56 88 98 80
5 d 43 88 78 69
```
*(Note: The sixth column represents the calculated average grade for each student.)*
---
## 5. Key Considerations & Best Practices
1. **Buffer Overflow Prevention**: In the `scanf` function, reading strings using `%s` into `stu.name` can cause a buffer overflow if the input name exceeds 19 characters. For production-grade code, use limits like `%19s` to prevent memory corruption.
2. **Integer vs. Floating-Point Division**: In this example, the average grade is calculated using integer division: `(math + English + C) / 3`. If you require precise decimal averages, change the `avargrade` data type to `float` or `double` and divide by `3.0`.
3. **File Path**: The file `"stud"` is created in the program's working directory. Ensure your execution environment has write permissions for that directory.
YouTip