C Files Lab and Quiz- C Programming For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Chapter 11 · Lecture 5

C Files Lab and Quiz

Build a binary sensor log with fwrite and fread, inspect it with a hex dump, then test yourself with a quiz and C file handling interview questions for embedded systems.

This final lecture of the opening section of Chapter 11 turns theory into practice. You will build a small sensor data logger in C that saves records in a binary file, reads them back, and also exports a readable text copy. It combines everything from the earlier lectures: streams, text versus binary, buffering, fopen modes and fclose. Then you will answer quiz questions and C file handling interview questions that employers commonly ask. This is the kind of hands-on exercise that makes our free C programming course useful for embedded C programming jobs, and a good checkpoint in any free embedded C course.

What You Will Learn

  • How to store fixed-size records with fwrite and load them with fread
  • How to guard against struct padding with _Static_assert
  • How to check the return values that matter: fopen, fwrite, fread, fclose
  • How to verify the file layout with od
  • How to answer common C file handling interview questions

Prerequisites

Lectures 1 to 4 of Chapter 11, plus structures and fixed-width integer types. The fread and fwrite functions are covered in depth later in this free C tutorial; here you only need to know that they transfer a number of items of a given size.

Lab: Binary Sensor Log

The goal

A device samples temperature from one or two sensors. Each sample stores the time in milliseconds, the temperature in tenths of a degree, the sensor number and a flags byte. We save three samples to samples.bin, load them again, print them, and write the same data as comma separated text to samples.txt.

One sample record: 8 bytes in the file
tick_ms: uint32_t (4 bytes) temp_x10: int16_t (2 bytes) sensor_id: uint8_t (1 byte) flags: uint8_t (1 byte)

Why store temperature times ten?

Many microcontrollers have no floating point unit. Storing 24.5 degrees as the integer 245 keeps the record small, exact and fast, and the decimal point is added only when printing.

The program

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

struct sample {
    uint32_t tick_ms;
    int16_t  temp_x10;   /* temperature in tenths of a degree C */
    uint8_t  sensor_id;
    uint8_t  flags;
};

_Static_assert(sizeof(struct sample) == 8, "unexpected padding in struct sample");

static int save_log(const char *path, const struct sample *s, size_t n)
{
    FILE *fp = fopen(path, "wb");
    if (fp == NULL) {
        perror(path);
        return -1;
    }
    size_t done = fwrite(s, sizeof *s, n, fp);
    if (fclose(fp) != 0 || done != n) {
        fprintf(stderr, "short write to %s\n", path);
        return -1;
    }
    return 0;
}

static int load_log(const char *path, struct sample *s, size_t max)
{
    FILE *fp = fopen(path, "rb");
    if (fp == NULL) {
        perror(path);
        return -1;
    }
    size_t n = fread(s, sizeof *s, max, fp);
    fclose(fp);
    return (int)n;
}

int main(void)
{
    struct sample out[3] = {
        { 1000, 245, 1, 0 },
        { 2000, 251, 1, 0 },
        { 3000, 398, 2, 1 },
    };
    struct sample in[8];

    if (save_log("samples.bin", out, 3) != 0)
        return EXIT_FAILURE;

    int n = load_log("samples.bin", in, 8);
    if (n < 0)
        return EXIT_FAILURE;

    printf("records read back: %d (record size %zu bytes)\n", n, sizeof(struct sample));
    for (int i = 0; i < n; i++)
        printf("tick=%u ms  sensor=%u  temp=%d.%d C  flags=%u\n",
               (unsigned)in[i].tick_ms, (unsigned)in[i].sensor_id,
               in[i].temp_x10 / 10, in[i].temp_x10 % 10, (unsigned)in[i].flags);

    /* a human readable copy for debugging */
    FILE *fp = fopen("samples.txt", "w");
    if (fp == NULL) {
        perror("samples.txt");
        return EXIT_FAILURE;
    }
    for (int i = 0; i < n; i++)
        fprintf(fp, "%u,%u,%d,%u\n", (unsigned)in[i].tick_ms,
                (unsigned)in[i].sensor_id, in[i].temp_x10, (unsigned)in[i].flags);
    fclose(fp);
    return EXIT_SUCCESS;
}

Build, run and inspect

$ gcc -Wall -Wextra -std=c11 -o sensor_log sensor_log.c
$ ./sensor_log
records read back: 3 (record size 8 bytes)
tick=1000 ms  sensor=1  temp=24.5 C  flags=0
tick=2000 ms  sensor=1  temp=25.1 C  flags=0
tick=3000 ms  sensor=2  temp=39.8 C  flags=1

$ cat samples.txt
1000,1,245,0
2000,1,251,0
3000,2,398,1

$ od -An -tx1 samples.bin
 e8 03 00 00 f5 00 01 00 d0 07 00 00 fb 00 01 00
 b8 0b 00 00 8e 01 02 01

Decode the hex dump

The binary file is 24 bytes: three records of 8 bytes. Take the first record, e8 03 00 00 f5 00 01 00, and read it field by field on this little-endian machine.

BytesFieldLittle-endian valueMeaning
e8 03 00 00tick_ms0x000003E8 = 10001000 ms
f5 00temp_x100x00F5 = 24524.5 degrees
01sensor_id1Sensor 1
00flags0No flags
First record as stored in samples.bin
e8 03 00 00 f5 00 01 00

Design decisions worth noticing

  • _Static_assert stops compilation if the compiler adds padding, so the file layout is the one you documented.
  • Fixed-width types make the field sizes the same on every platform.
  • fclose is checked in save_log, because that call can reveal a failed final write.
  • fread returns how many complete records it got, so the caller prints only that many.
  • The text copy uses fprintf; anyone can open it in a spreadsheet.
Warning: this file is portable only between machines with the same byte order. Writing a struct directly is fast and fine for a private log on one device. For data shared with other systems, write each field in a defined byte order or use a text format.

Challenges to try

  1. Change save_log to open with "ab" so each run adds records instead of replacing the file, then read back and count them.
  2. Create a boot counter: read an integer from boot.cnt with "r" (use 0 if it does not exist), add one, and write it back with "w".
  3. Use "wx" to create samples.bin and print a clear message when it already exists.
  4. Add a 4-byte magic number and a version byte at the start of the file and check them when loading.

Common Mistakes in This Lab

MistakeSymptomFix
Opening the binary log with "w" instead of "wb"Works on Linux, corrupts data on WindowsAlways use the b flag
Printing in[i] beyond nGarbage valuesLoop to the count returned by fread
Skipping the sizeof checkDifferent record size on another compilerAdd _Static_assert
Dividing a negative temp_x10 by ten and printing the remainderOdd output such as -3.-5Print the sign separately and use the absolute value

Chapter Summary and Key Takeaways

Revise this summary before you attempt the C file handling interview questions further down.

  • Files give a program persistent memory; stdio streams are the portable way to use them.
  • Text files store characters; binary files store bytes exactly as in memory and depend on type size and byte order.
  • Data sits in a buffer until it is flushed or the file is closed.
  • "w" erases, "a" appends, "r" reads, the plus modes combine, b marks binary and x protects against overwriting.
  • Always check fopen for NULL, report errors with perror, and close every file you open.

Quiz Before the C File Handling Interview Questions

Pick an answer before you open the solution.

  1. What does fopen return when it cannot open the file?
    1. -1
    2. 0 as an int
    3. NULL
    4. EOF
    Show answer

    C. NULL, and errno is set.

  2. Which mode erases the contents of an existing file when it is opened?
    1. "r"
    2. "a"
    3. "r+"
    4. "w"
    Show answer

    D. "w" truncates the file to zero length.

  3. How many bytes does the text “1679” occupy in a text file (no newline)?
    1. 2
    2. 4
    3. 8
    4. It depends on the CPU
    Show answer

    B. One byte per digit character.

  4. What does fflush(fp) do?
    1. Deletes the file
    2. Sends buffered output to the operating system
    3. Closes the file
    4. Guarantees data is on the physical disk
    Show answer

    B. It hands data to the kernel; it does not guarantee physical storage.

  5. Which standard stream is unbuffered by default?
    1. stdin
    2. stdout
    3. stderr
    4. none of them
    Show answer

    C. stderr.

  6. What happens with fopen("data.bin", "r+") if data.bin does not exist?
    1. It is created
    2. It returns NULL
    3. It is created and truncated
    4. The program exits
    Show answer

    B. "r+" requires an existing file.

  7. Which mode always places new data at the end of the file?
    1. "a"
    2. "w"
    3. "r+"
    4. "rb"
    Show answer

    A. Append mode (and "a+") writes at the end regardless of the position.

  8. Why use uint16_t instead of int in a binary file format?
    1. It is faster to type
    2. Its size is fixed, int is not
    3. Only uint16_t can be written with fwrite
    4. It avoids endianness
    Show answer

    B. int may be 16 or 32 bits; uint16_t is always 16. Endianness still applies.

  9. What is wrong with using a FILE * after fclose?
    1. Nothing
    2. Undefined behaviour
    3. It reopens the file
    4. It only produces a warning
    Show answer

    B. The stream no longer exists.

  10. What effect does the b in "rb" have on Linux?
    1. It makes the file read-only
    2. It converts line endings
    3. None, but it keeps code portable
    4. It enables buffering
    Show answer

    C. POSIX systems ignore it, and other platforms rely on it.

Predict the Result: C File Handling Interview Questions Warm-Up

  1. A file contains AB followed by a newline. You open it with "a" and write C plus a newline. What is in the file?
    Show answer

    Two lines: AB and C. Append mode keeps the old data.

  2. A 100-byte file is opened with "w+". What is its size immediately after fopen succeeds?
    Show answer

    0 bytes. The write modes truncate on open.

  3. What is wrong with fp = fopen("x.txt", 'r');?
    Show answer

    The mode must be a string. A character constant is an integer, which does not match the pointer parameter and gives undefined behaviour at run time.

C File Handling Interview Questions

These C file handling interview questions run from basic to practical. Try to answer aloud before you open each one.

1. What is the difference between a text file and a binary file?

Text files hold characters and line endings and are human readable; binary files hold raw memory bytes. Binary is faster and smaller for numbers but depends on type sizes, padding and byte order, while text is portable.

2. Why must you check the return value of fopen?

It returns NULL on any failure: missing file, permission problem, full disk, too many open files. Using the NULL pointer afterwards crashes the program. Check it and report the reason with perror.

3. What is the difference between “w” and “a”?

"w" truncates an existing file or creates a new one; "a" keeps existing data and writes only at the end.

4. What is buffering and why is it used?

Output is collected in memory and written in larger blocks, which reduces the number of expensive system calls and device accesses. The trade-off is that data may be lost if the program dies before the buffer is flushed.

5. What is the difference between fflush and fsync?

fflush moves data from the stdio buffer to the kernel. fsync, a POSIX call, asks the kernel to write its cached data to the storage device. For power-loss safety you need both.

6. What happens to buffered data if the program crashes?

It is lost, because the stdio buffer lives in the process memory and is not flushed. Normal return from main and exit flush it; abort or a kill signal do not.

7. How are stdio functions different from open, read and write?

stdio is portable standard C with buffering and formatted I/O through FILE *. The others are POSIX system calls using integer file descriptors, with no buffering, giving precise control for device files and sockets.

8. How can you avoid overwriting an existing file by accident?

Open with "wx" (C11), or on POSIX use open with O_CREAT | O_EXCL. This makes the check and the creation a single atomic step.

9. Why is it risky to fwrite a struct to a file that other systems will read?

Padding, member sizes and byte order can differ by compiler and CPU. Use fixed-width types, check the size with _Static_assert, write fields in a defined byte order, or choose a text format.

10. How would you update a configuration file safely on an embedded Linux device?

Write the new content to a temporary file in the same directory, flush and fsync it, then call rename to replace the original. If power fails, you keep either the complete old file or the complete new one.

Frequently Asked Questions

Where can I practise C file handling interview questions?

Work through the interview section above, rebuild the sensor logger from memory, and then try the four challenges. This free C programming course adds more practice at the end of each chapter.

Where can I learn C file handling for free?

This free C programming course from EmbeddedPathashala covers file handling step by step with tested examples, quizzes and interview questions.

Is C file handling used in embedded systems?

Yes. Embedded Linux devices read configuration and write logs with stdio, and microcontrollers use the same ideas with SD cards and flash file systems such as FatFs.

Should I use fread and fwrite or fprintf for logs?

Use fprintf when people must read the log; use fwrite for compact, high-rate data that tools will decode.

How do I view a binary file?

Use od -An -tx1 file or hexdump -C file on Linux.

What should I study after this?

Reading and writing functions: fgetc, fputc, fgets, fread, fwrite, followed by file positioning with fseek and ftell.

Does this free embedded C course need special hardware?

No. A Linux PC with gcc is enough for every example in this chapter.

Ready for reading and writing functions?

Bookmark these C file handling interview questions, then continue the free C tutorial with character, string and block I/O on files, and file positioning.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →