What are fgetc in C: Read Characters- Free Embedded C Programming Course

🚀 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 · Files · Lecture 10

fgetc in C: Read Characters

Read a file one character at a time, and discover why storing the result in a char breaks loops on ARM.

Reading is the mirror image of writing, but it hides a trap that only bites on some processors. fgetc in C reads one character from a stream, and the one-line detail of what type you store its result in decides whether your loop is correct or silently broken. In this lecture of our free C programming course you will read a file character by character, dump its bytes in hexadecimal, and reproduce the famous char versus int bug on both a signed-char and an unsigned-char build.

The old textbook mentions in one sentence that the variable must be an int. We go further: we show exactly what goes wrong, why it depends on the CPU, and why this matters for embedded C programming on ARM boards. All programs were compiled and run for this lecture.

What You Will Learn

In this free C tutorial you will:

  • Use fgetc in C in the correct loop shape.
  • Explain the range of its return value and why EOF needs an int.
  • Reproduce the char versus int bug and see the compiler warning for it.
  • Compare the read-in-condition loop with the priming-read loop.
  • Know when to use getc, getchar, ungetc and block reads.

Prerequisites

You should have read the lectures on EOF and on fputc(). You also need a basic idea of signed and unsigned integer types: a signed 8-bit value can hold -128 to 127, an unsigned one 0 to 255.

fgetc in C: Syntax and Return Value

int fgetc(FILE *stream);

The function reads the next byte from the stream, advances the file position by one and returns the byte as an unsigned char converted to int. The book phrases this as “converted to an int without sign extension”. When no byte is available it returns EOF, and as the earlier lecture explained, you then use feof() and ferror() to tell a normal end from a failure.

All possible results of fgetc

Byte 0Byte 1…Byte 255EOF (-1)
 
Values 0 to 255 are real data. -1 is outside that range, so it can never be confused with data, but only if you keep it in an int.

Dumping a File Byte by Byte

The first program reads a file given on the command line and prints every byte as a hexadecimal value together with its character, replacing unprintable characters with a dot. It is a tiny version of the xxd tool and is handy when debugging file formats.

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

/* Print every byte of a file as a hex value plus its character. */
int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s <file>\n", argv[0]);
        return EXIT_FAILURE;
    }
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    int c;
    long offset = 0;
    while ((c = fgetc(fp)) != EOF) {
        printf("offset %2ld : 0x%02X  %c\n", offset, c,
               isprint(c) ? c : '.');
        offset++;
    }
    fclose(fp);
    return EXIT_SUCCESS;
}
gcc -Wall -Wextra -o ep_dump ep_dump.c
printf 'Hi!\n' > hi.txt
./ep_dump hi.txt
offset  0 : 0x48  H
offset  1 : 0x69  i
offset  2 : 0x21  !
offset  3 : 0x0A  .

Four bytes were read: the three visible characters and the newline, which prints as a dot. Notice that the loop condition is (c = fgetc(fp)) != EOF. The assignment and the comparison are in the same expression, so there is exactly one read per iteration.

The char Versus int Bug With fgetc in C

Now the trap. The program below writes five bytes, 41 42 FF 43 44, to a binary file. It then reads them twice: once storing each result in a char, once in an int. The middle byte, 0xFF, is a perfectly ordinary data value.

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

int main(void)
{
    /* five bytes; the middle one is 0xFF */
    const unsigned char data[] = { 0x41, 0x42, 0xFF, 0x43, 0x44 };
    FILE *fp = fopen("bytes.bin", "wb");
    if (!fp)
        return EXIT_FAILURE;
    fwrite(data, 1, sizeof data, fp);
    fclose(fp);

    /* Wrong: storing the result in a plain char */
    fp = fopen("bytes.bin", "rb");
    char ch;
    int seen_char = 0;
    while ((ch = (char)fgetc(fp)) != EOF)
        seen_char++;
    fclose(fp);
    printf("char variable : read %d of 5 bytes\n", seen_char);

    /* Right: keep the result in an int */
    fp = fopen("bytes.bin", "rb");
    int c, seen_int = 0;
    while ((c = fgetc(fp)) != EOF)
        seen_int++;
    fclose(fp);
    printf("int variable  : read %d of 5 bytes\n", seen_int);
    return 0;
}
gcc -Wall -Wextra -o ep_charbug ep_charbug.c
./ep_charbug
char variable : read 2 of 5 bytes
int variable  : read 5 of 5 bytes

With a char variable the loop stopped after two bytes. The reason is arithmetic. The byte 0xFF is stored into a signed char, where it means -1. That equals EOF, so the loop believes the file has ended. The three remaining bytes are silently ignored, and nothing reported an error.

What happens on ARM and other unsigned-char targets

Whether plain char is signed is up to the compiler. The ARM ABI makes it unsigned, so on a Cortex-M or Cortex-A board the failure is different and worse. A byte can never become -1, so the comparison with EOF is never true and the loop never ends. You can mimic that on your PC with the GCC option -funsigned-char. The next program has a guard so it cannot hang. It reads bytes.bin from the previous example.

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

/* Same mistake as ex10_2, but with a loop guard so it cannot hang.
 * Build once normally and once with -funsigned-char to mimic ARM targets. */
int main(void)
{
    FILE *fp = fopen("bytes.bin", "rb");
    if (fp == NULL) {
        perror("bytes.bin");
        return EXIT_FAILURE;
    }

    char ch;
    int reads = 0;
    printf("plain char is %s on this build\n", ((char)-1 < 0) ? "signed" : "unsigned");

    while ((ch = (char)fgetc(fp)) != EOF) {
        reads++;
        if (reads >= 50) {
            puts("giving up after 50 reads: EOF was never detected");
            break;
        }
    }
    printf("loop ended after %d reads\n", reads);
    fclose(fp);
    return 0;
}
gcc -Wall -Wextra -o ep_signed ep_unsigned.c
gcc -Wall -Wextra -funsigned-char -o ep_unsigned ep_unsigned.c
./ep_signed
./ep_unsigned
plain char is signed on this build
loop ended after 2 reads
plain char is unsigned on this build
giving up after 50 reads: EOF was never detected
loop ended after 50 reads

The same source behaves in two opposite ways depending on one compiler flag. On the unsigned build, GCC also warns during compilation: comparison is always true due to limited range of data type. That warning is the compiler telling you the exact problem, which is one more reason to build embedded code with -Wall -Wextra and read every message.

Variable typeByte 0xFF becomesResult with EOF test
signed char (x86 default)-1Loop stops early, data lost
unsigned char (ARM default)255EOF never matches, loop may never end
int255, and EOF stays -1Correct on every platform

Two Correct Loop Shapes

There are two accepted ways to write the loop. Both keep the result in an int. The book shows the second form as the expanded equivalent of the first.

Shape A: read inside the condition

  • while ((c = fgetc(fp)) != EOF) { ... }
  • Shortest form; only one read statement to maintain.

Shape B: priming read

  • Read once before the loop, then read again as the last statement of the body.
  • Useful when the loop body has several continue statements, or when you need to look at the first character before deciding what to do.

Here is shape B in a complete program that counts the digit characters in a file:

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

/* Count the digit characters in a file using the "priming read" loop shape. */
int main(void)
{
    FILE *fp = fopen("mixed.txt", "w");
    if (fp == NULL)
        return EXIT_FAILURE;
    fputs("a1b22c333", fp);
    fclose(fp);

    fp = fopen("mixed.txt", "r");
    if (fp == NULL)
        return EXIT_FAILURE;

    int digits = 0;
    int c = fgetc(fp);              /* read once before the loop  */
    while (c != EOF) {
        if (isdigit(c))
            digits++;
        c = fgetc(fp);              /* read again at the loop end */
    }
    fclose(fp);

    printf("digits found: %d\n", digits);
    return 0;
}
gcc -Wall -Wextra -o ep_digits ep_digits.c
./ep_digits
digits found: 6

The file contains a1b22c333, which holds 1 + 2 + 3 = 6 digits. The danger of shape B is forgetting the second read, which makes the loop run forever on the same character. Many teams prefer shape A for that reason.

getc, getchar and ungetc

FunctionReads fromNote
fgetc(fp)Any streamAlways a function
getc(fp)Any streamMay be a macro; avoid side effects in the stream argument
getchar()stdinEquivalent to getc(stdin)
ungetc(c, fp)Pushes a character backLets parsers peek ahead by one character

The book states that getc() and fgetc() differ only in being a macro and a function. That is the standard’s allowance and not something to depend on. Treat them as the same operation, with the single caution about side effects.

Real-World Uses of fgetc in Embedded C Programming

  • Tokenisers: a configuration parser reads a character, decides whether it starts a name, a number or a comment, and uses ungetc() to return the one it peeked.
  • Checksum tools: a quick CRC of a firmware image reads each byte with fgetc() and updates the checksum.
  • Serial console parsers: a command shell reads characters from a stream attached to a UART and assembles a command line.
  • Sysfs readers: a monitor opens a small text file such as a temperature entry, reads its few characters and converts them.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Storing the result in charEarly stop on 0xFF or an endless loopUse int
Looping on feof()One extra iterationTest the read result
Stopping when the value is 0Binary file truncated at the first zero byteOnly EOF ends the loop
Printing the result with %c before testingStrange output at the endTest for EOF first
Opening a binary file in text mode on WindowsBytes changed or file ends earlyUse "rb"
Forgetting the second read in a priming loopEndless loopPrefer the read-in-condition shape

Best Practices for fgetc in C

  • When using fgetc in C, declare the variable as int c, always, and add a comment saying why.
  • Compile with -Wall -Wextra and treat type-limit warnings as bugs.
  • After the loop, call ferror() to separate a normal end from a failure.
  • If you pass the character to isdigit() or toupper(), the value must be representable as unsigned char or equal to EOF, which an int from fgetc() already satisfies.
  • Use fgets() for text lines and fread() for binary blocks when speed matters.

Performance and security notes

Each call to fgetc() checks the stdio buffer, which is cheap but not free. On large inputs block reads can be many times faster. For security, a loop that copies characters into a fixed array must also check the array size; reading until EOF into a small buffer is a classic overflow. Count the characters and stop when the buffer is full.

Key Takeaways

Remember these points

  • fgetc in C returns a value from 0 to 255 or EOF.
  • Keep the result in an int. A char breaks the loop on every platform, in a different way on each.
  • x86 compilers usually use signed char; ARM uses unsigned, so a bug can hide on your PC.
  • The compiler warning about limited range points straight at this bug.
  • Loop on the read result, never on feof().
  • ungetc() gives a parser one character of look-ahead.

Conclusion

With fgetc in C, a single declaration, int instead of char, separates a correct reader from one that loses data or never finishes. You saw both failures on the same file, learned that the outcome depends on the compiler’s choice for plain char, and met a warning that catches the mistake for free.

The next lecture of this free C tutorial moves from characters to whole integers, using putw() and getw(), where a similar ambiguity with EOF returns in an even more dangerous form.

Frequently Asked Questions

What does fgetc return?

It returns the next character from the stream, read as an unsigned char and converted to int, so the value is between 0 and 255. When there is nothing more to read, or on a read error, it returns EOF.

Why must the variable be an int and not a char?

There are 257 possible results: 256 byte values plus EOF. A one-byte type cannot hold them all. On a platform where char is signed, the byte 0xFF becomes -1 and looks like EOF. Where char is unsigned, EOF is never recognised and the loop does not end.

Is char signed or unsigned in C?

It is implementation-defined. Compilers for x86 Linux usually make it signed, while the ARM application binary interface makes it unsigned, which matters because many embedded boards use ARM cores.

What is the difference between fgetc and getc?

Their results are the same. getc() may be a macro that evaluates its stream argument more than once, while fgetc() is always a function. getchar() is getc(stdin).

How can I look at a character without consuming it?

Read it with fgetc() and push it back with ungetc(c, fp). One character of pushback is guaranteed. Parsers use this to peek at the next character.

Does fgetc work on binary files?

Yes, if you open the file with "rb". It then returns every byte value from 0 to 255 untouched. Do not stop the loop when you see the value 0; only EOF means the end.

Is reading one character at a time slow?

It has per-call overhead, although stdio buffers the underlying read. For large files use fgets() for lines or fread() for blocks.

Continue the Free Embedded C Course

Next: store integers in binary files with putw and getw, see why they are legacy functions, and finish the chapter with a hands-on ADC logging lab and quiz.

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

1 Comment

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 →