What are fprintf fscanf Standard Streams- C Programming Course in Telugu

🚀 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: Files

fprintf fscanf Standard Streams

Learn how stdin, stdout and stderr work as FILE pointers, and write one C function that prints to the screen or a file.

Welcome to the next lecture of our free C programming course. You have already used fprintf() and fscanf() with files that you opened yourself. Today you will see that the console is just another file: stdin, stdout and stderr are FILE * pointers opened for you before main() starts. Once you understand this, you can write embedded C programming code that logs to a serial console on the bench and to a file on a Linux gateway using the same function. This free C tutorial keeps every example small and runnable.

What You Will Learn

  • Why stdin, stdout and stderr are ordinary FILE pointers with descriptors 0, 1 and 2
  • How printf() relates to fprintf(stdout, …) and scanf() to fscanf(stdin, …)
  • How to write one output function that works for the screen and for files
  • Why the fscanf() return value, not EOF, should control a safe read loop
  • How to redirect streams from the shell

Prerequisites

  • fopen(), fclose() and the fprintf()/fscanf() basics from the earlier Files lectures
  • Format specifiers from the Input-Output chapter
  • A C compiler such as gcc on Linux

Standard Streams in C: stdin, stdout and stderr

Before main() runs, the C runtime opens three streams for you. Each one is a normal FILE *, which is why every file function you already know can use them.

StreamDescriptorDefault deviceBufferingShortcut function
stdin0KeyboardLine buffered on a terminalscanf(), getchar()
stdout1Terminal screenLine buffered on a terminal, fully buffered when redirectedprintf(), putchar(), puts()
stderr2Terminal screenUnbufferedNo shortcut: use fprintf(stderr, …) or perror()
One function, many destinations
print_report(out)→FILE *out
out = stdout→Terminal
out = fp→report.txt on disk
out = stderr→Terminal, unbuffered

printf and fprintf Share One Engine

The shortcut functions you learned in the Input-Output chapter are thin wrappers. Writing to the screen with printf() and writing to a stream with fprintf(stdout, …) produce the same bytes. Reading with scanf() and fscanf(stdin, …) behave the same way. The program below uses all four forms so you can see them side by side.

#include <stdio.h>

int main(void)
{
    int level = 7;
    char name[16];

    printf("via printf : level=%d\n", level);
    fprintf(stdout, "via fprintf: level=%d\n", level);
    fprintf(stderr, "diagnostic message on stderr\n");

    printf("Enter name and level: ");
    fflush(stdout);

    if (fscanf(stdin, "%15s %d", name, &level) == 2)
        printf("Read: name=%s level=%d\n", name, level);
    else
        printf("Input did not match the pattern\n");

    return 0;
}

Build and run it:

gcc -Wall -Wextra -std=c11 -o ep_streams ep_streams.c
./ep_streams

Typical terminal session (the last line you type is Asha 4):

via printf : level=7
via fprintf: level=7
diagnostic message on stderr
Enter name and level: Asha 4
Read: name=Asha level=4

Note: fflush(stdout) before reading makes sure the prompt is visible even when stdout is redirected or the prompt has no newline.

Write Once, Print Anywhere with a FILE Pointer

Because a stream is just a pointer, a function that takes FILE *out does not care where its text goes. This is the most useful trick in this lecture for embedded C programming: during bring-up you point the function at the console, and in the field you point it at a log file or a retargeted serial port.

#include <stdio.h>

static void print_report(FILE *out, const char *title, int count, float avg)
{
    fprintf(out, "== %s ==\n", title);
    fprintf(out, "samples : %d\n", count);
    fprintf(out, "average : %.2f\n", avg);
}

int main(void)
{
    FILE *fp = fopen("report.txt", "w");

    print_report(stdout, "Live report", 12, 24.5f);

    if (fp == NULL) {
        perror("report.txt");
        return 1;
    }
    print_report(fp, "Saved report", 12, 24.5f);
    fclose(fp);
    return 0;
}
gcc -Wall -Wextra -std=c11 -o ep_report ep_report.c
./ep_report
cat report.txt
== Live report ==
samples : 12
average : 24.50
== Saved report ==
samples : 12
average : 24.50

The first three lines come from the screen, and the second three are the contents of report.txt. One function, two destinations.

Reading with fscanf: Trust the Return Value

fscanf() returns how many items it successfully converted. That number, not EOF alone, tells you whether a line was good. Here is a reader for a file of label value pairs.

temp1 23.5
temp2 24.25
humid 61
#include <stdio.h>

int main(void)
{
    char label[16];
    float value;
    int lines = 0;
    FILE *fp = fopen("readings.txt", "r");

    if (fp == NULL) {
        perror("readings.txt");
        return 1;
    }

    while (fscanf(fp, "%15s %f", label, &value) == 2) {
        printf("%-8s -> %6.2f\n", label, value);
        lines++;
    }

    if (ferror(fp))
        perror("read error");
    else if (!feof(fp))
        printf("Stopped early: bad data after line %d\n", lines);

    fclose(fp);
    return 0;
}
gcc -Wall -Wextra -std=c11 -o ep_fscanf_loop ep_fscanf_loop.c
./ep_fscanf_loop
temp1    ->  23.50
temp2    ->  24.25
humid    ->  61.00

Now damage the file so the second line reads temp2 oops. A loop written as != EOF would spin forever, because fscanf returns 0 and never consumes the bad text. Our loop stops because 0 is not equal to 2, and the check after the loop explains why:

temp1    ->  23.50
Stopped early: bad data after line 1
fscanf returnsMeaningWhat your code should do
Same as number of conversionsEvery item matchedUse the values
Smaller positive numberSome items matched, then text did not fit the formatReport a format error
0First conversion failed on this textReport a format error, do not loop again
EOFEnd of input or read error before any conversionCheck feof() and ferror()

Redirecting Streams from the Shell

Since your program only talks to stdin, stdout and stderr, the shell can swap what they are connected to without any code change. Create an input file and run the first program again:

echo "Ravi 9" > in.txt
./ep_streams < in.txt > out.txt 2> err.txt
cat out.txt
cat err.txt
via printf : level=7
via fprintf: level=7
Enter name and level: Read: name=Ravi level=9
diagnostic message on stderr

The error line went to its own file while the normal output went to out.txt. Separating the two is how real tools keep logs clean.

Common Mistakes with Standard Streams

MistakeWhat goes wrongFix
fscanf(fp, “%s”, buf) with no widthLong input overflows bufUse a width one less than the array: “%15s” for char[16]
Looping on != EOF onlyInfinite loop on malformed textCompare with the expected conversion count
fprintf(fp, user_text)A % in the text is treated as a formatAlways fprintf(fp, “%s”, user_text)
Skipping the fopen NULL checkCrash on first use of fpTest fp and call perror()
Wrong specifier such as %d for a floatGarbage valuesMatch the specifier to the argument type

Best Practices, Performance and Security

  • Send diagnostics to stderr and data to stdout so redirection stays useful.
  • Give every %s in fscanf a field width.
  • Write helper functions that accept a FILE * parameter instead of hard-coding stdout.
  • Console output is slow compared with computation, so avoid printing inside tight loops on a device with a slow UART.
  • Never pass untrusted text as the format string.

Summary and Key Takeaways

  • stdin, stdout and stderr are FILE pointers that exist before main() runs.
  • printf(x) equals fprintf(stdout, x) and scanf(x) equals fscanf(stdin, x).
  • A function that takes FILE *out can print to the console or any file.
  • Check that fscanf returns the number of conversions you expect.
  • Use stderr for diagnostics and the shell to redirect either stream.

Conclusion

Treating the console as a file is a small idea with big payoff: your formatting code is written once and reused everywhere. In the next lecture of this free embedded C course we leave text behind and store raw structures and arrays in binary files.

Frequently Asked Questions

Is printf the same as fprintf(stdout, …)?

Yes. printf() is defined as writing to the stdout stream, so printf(fmt, …) behaves exactly like fprintf(stdout, fmt, …). The same relation holds between scanf() and fscanf(stdin, …).

Why does stderr show text immediately while stdout can lag behind?

stderr is unbuffered so error messages appear at once, while stdout is line buffered on a terminal and fully buffered when redirected. Call fflush(stdout) when you need the two streams to interleave predictably.

What does fscanf return?

It returns the number of input items it converted and stored. It returns EOF if input ends or fails before the first conversion, and a smaller number (possibly 0) when the text does not match the format.

Why does my while(fscanf(…) != EOF) loop never finish on bad data?

On a matching failure fscanf returns 0, not EOF, and leaves the offending characters unread. The loop condition stays true and the same bad text is rejected forever. Compare against the expected number of conversions instead.

How do I send program output to a file without changing the code?

Use shell redirection: ./prog > out.txt sends stdout to a file and ./prog 2> err.txt sends stderr to another file. This works because the program only ever talks to the stdout and stderr streams.

Do stdin, stdout and stderr exist on a microcontroller?

The names exist in the C library, but they only reach real hardware if your toolchain is told where to send the bytes. Many embedded toolchains let you retarget the low-level write function to a UART so printf() prints on a serial console.

Continue the Free C Programming Course

Next up: binary block I/O. Learn how fread() and fwrite() move whole structures in a single call.

💬 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 →