🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Append and Grade Records
Free C programming course: add records with “ab” mode and read them back to calculate grades
Real programs rarely create a file once and forget it. They add new data over time. In this lecture of our free C programming course you will learn append mode in C, write records to the end of an existing binary file, and then read the whole file to compute and print a grade for every record. The same approach drives event logs and measurement history in embedded C programming, so it belongs in any free embedded C course.
This free C tutorial for C programming for embedded systems uses an original structure and original programs. Both were compiled and run; the file sizes and output below are real.
What You Will Learn in This Free C Programming Course
- How “ab” append mode behaves and why it does not erase old data
- How to write records safely with bounded scanf() input
- How to read every record in a loop with fread()
- How to turn a score into a grade with a small helper function
- How to check the file size to prove records were added
Prerequisites for the Free C Programming Course
You need the earlier lectures on fopen() modes, fwrite() and fread(), and the position pointer lectures in this chapter.
How Append Mode Works in C
The mode string "ab" opens a binary file for writing at the end. If the file does not exist, it is created. If it exists, its contents are kept. Compare this with "wb", which empties an existing file the moment you open it.
| Mode | File missing | File exists | Where writes go |
|---|---|---|---|
| “wb” | Created | Truncated to zero length | From byte 0 |
| “ab” | Created | Kept | Always at the end |
| “rb+” | Open fails | Kept | Wherever the pointer is |
Append ignores fseek() for writes
In append mode every write is placed at the current end of the file, even if you moved the pointer with fseek(). You can still use fseek() to read from other places if the mode allows reading (“ab+”), but you cannot overwrite earlier data in append mode. Use “rb+” when you need in-place updates; the next lecture shows that.
File growth across two program runs
| Step | Records in file | Size in bytes |
|---|---|---|
| File does not exist | 0 | none |
| Run 1 adds Asha and Bala | 2 | 48 |
| Run 2 adds Chitra | 3 | 72 |
Where new records land
Program 1: Append Student Records
We use a structure called pupil with a 16 byte name, a roll number and a score. Its size is 24 bytes on a typical 32-bit or 64-bit system.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct pupil {
char name[16];
int roll;
float score;
};
int main(void)
{
FILE *fp = fopen("pupils.dat", "ab");
if (fp == NULL) { perror("fopen"); return 1; }
for (;;) {
struct pupil p;
memset(&p, 0, sizeof p);
printf("name (or 'end'): ");
if (scanf("%15s", p.name) != 1 || strcmp(p.name, "end") == 0)
break;
printf("roll and score : ");
if (scanf("%d %f", &p.roll, &p.score) != 2) {
fprintf(stderr, "bad input, stopping\n");
break;
}
if (fwrite(&p, sizeof p, 1, fp) != 1) {
perror("fwrite");
break;
}
}
fclose(fp);
return 0;
}
Notice three safety habits. The format %15s limits input to 15 characters so the name always fits with its terminator. The return value of scanf() is checked. And a sentinel word, end, stops the loop, so you do not have to ask “do you want more” after every record.
Build and run
gcc -std=c11 -Wall -Wextra -o append_pupils append_pupils.c
./append_pupils
name (or 'end'): Asha
roll and score : 101 86.5
name (or 'end'): Bala
roll and score : 102 72
name (or 'end'): end
ls -l pupils.dat
After this first run the file is 48 bytes (two records of 24). Run the program again and add one more person:
./append_pupils
name (or 'end'): Chitra
roll and score : 103 55.5
name (or 'end'): end
ls -l pupils.dat
The file is now 72 bytes. The old records are intact, which proves append mode worked.
Program 2: Read Records and Calculate Grades
The grading rule is a simple three-band scale: 80 or above is A, 60 up to 80 is B, below 60 is C. We put the rule in its own function so that it is easy to test and change.
#include <stdio.h>
struct pupil {
char name[16];
int roll;
float score;
};
static char grade_of(float score)
{
if (score >= 80.0f) return 'A';
if (score >= 60.0f) return 'B';
return 'C';
}
int main(void)
{
FILE *fp = fopen("pupils.dat", "rb");
if (fp == NULL) { perror("fopen"); return 1; }
printf("%-16s %5s %7s %s\n", "NAME", "ROLL", "SCORE", "GRADE");
struct pupil p;
int rows = 0;
while (fread(&p, sizeof p, 1, fp) == 1) {
printf("%-16s %5d %7.1f %c\n", p.name, p.roll, p.score,
grade_of(p.score));
rows++;
}
printf("%d record(s)\n", rows);
fclose(fp);
return 0;
}
Build and run
gcc -std=c11 -Wall -Wextra -o grade_report grade_report.c
./grade_report
Expected output
NAME ROLL SCORE GRADE
Asha 101 86.5 A
Bala 102 72.0 B
Chitra 103 55.5 C
3 record(s)
Grade bands
| Score range | Grade | Example from the run |
|---|---|---|
| 80 and above | A | Asha 86.5 |
| 60 up to below 80 | B | Bala 72.0 |
| Below 60 | C | Chitra 55.5 |
Why the Read Loop Uses fread() == 1
The loop condition is the return value of fread(), not feof(). Testing feof() before reading is a well-known bug: the flag becomes true only after a read has already failed, so the loop runs one extra time with stale data. Reading first and testing the return value avoids that.
Real-World Use Cases
- A device appends one binary event record per fault and a service tool prints the history.
- A test rig appends one result per unit and a report program summarizes them.
- A data logger appends a sample every second to an SD card file.
Common Mistakes and Troubleshooting
%15s for a 16 byte buffer.fflush() after each record, and on Linux consider fsync().Best Practices and Security
- Check the return value of every fwrite() and close the file properly.
- Keep the grading rule in one function so you can unit test it.
- Validate the score range (for example 0 to 100) before writing it.
- Restrict the file permissions when the data is private.
Practice Exercises for Your Free C Programming Course
Try these extensions of the append and grade programs. They mirror the tasks a student in a free C programming course will meet in lab exams and in small embedded logging projects.
- Add a fourth grade, D, for scores below 40, and change the helper function only. Notice that the rest of the program stays the same.
- Print the class average and the highest scorer after the table. Keep track of the best record while reading.
- Reject scores below 0 or above 100 in the append program before writing them.
- Add a program that counts how many records are stored using only the file size and the record size.
- Run the append program three times and confirm with
ls -lthat the size grows by 24 bytes per record.
| Task | Key function |
|---|---|
| Add data | fopen “ab” and fwrite |
| Read all data | fread in a loop |
| Count records | fseek END, ftell, divide |
| Decide the grade | helper function |
Small projects like this are the best part of a free C programming course because they turn function names into working tools.
Summary and Key Takeaways
- “ab” creates the file if missing and keeps old data if present.
- Writes in append mode always go to the end.
- Read all records with
while (fread(...) == 1). - A small helper function keeps grading logic clean and testable.
Conclusion: Free C Programming Course Next Steps
You can now add data to a file over many runs and report on it later, which is the foundation of logging in embedded C programming. The final lecture in this group is a lab that updates a record in place and finishes with a quiz and interview questions to test what you learned in this free C programming course.
Frequently Asked Questions
What is append mode in C?
Opening a file with “a” or “ab” so that every write goes to the end and existing content stays.
Does “ab” create the file if it does not exist?
Yes.
Can I overwrite earlier records in append mode?
No. Use “rb+” with fseek() for in-place updates.
Why check fread() == 1 instead of feof()?
feof() becomes true only after a failed read, so testing it first causes an extra loop pass.
How can I make appended records survive a power cut?
Flush after each write, and on Linux call fsync() on the file descriptor.
Why limit scanf(“%s”) with a width?
To prevent buffer overflow when the input is longer than the array.
Finish This Free C Tutorial Chapter
Next: a hands-on file seeking lab, a quiz and interview questions.

2 Comments