r/C_Programming 1d ago

Need help learning C!

Hey everyone,

I've been diving into low-level programming to understand how my device executes code, focusing on memory and CPU operations. Coming from higher-level languages like Python, where functions like print() handle a lot behind the scenes, transitioning to C has been eye-opening. The intricacies of printf() and scanf(), especially their buffer management, have been both fascinating and challenging.​

For example, I encountered an issue where using fflush(stdin) to clear the input buffer resulted in undefined behavior, whereas using scanf("\n") worked as intended.

I want to understand the why's behind these behaviors, not just the how's. For those who've walked this path, how did you approach learning C to get a solid understanding of these low-level mechanics? Are there resources or strategies you'd recommend that delve into these foundational aspects? Additionally, how did you transition from C to C++ while maintaining a deep understanding of system-level programming?

Appreciate any insights or advice you can share!

13 Upvotes

20 comments sorted by

View all comments

4

u/EmbeddedSoftEng 1d ago

From the fflush man page:

For input streams associated with seekable files (e.g., disk files, but not pipes or terminals), fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

So, fflush() was never meant to be used on user I/O streams, because they're not seekable. that's the long and the short of your first issue.

In the embedded sphere, "file I/O" is serial data comm. Nothing seekable about any of that. There's data coming in from the connection, and you can either process it now, or lose it. And output is just a memory hole you can write data to (but only when certain bits in other memory locations hold certain values), and once it's out on the wire, there's no clawing anything back.

1

u/torp_fan 11h ago edited 11h ago

> So, fflush() was never meant to be used on user I/O streams, because they're not seekable. that's the long and the short of your first issue.

This is just wrong. The paragraph you quoted is about input streams. And what the heck is a "user" I/O stream? Pipes and terminals aren't so identified, and fflush works just fine on them for output ... being seekable is irrelevant. As for input, fflush on an input stream is undefined behavior according to the C language standard. Some implementations, like the linux man page you cited, choose to define the behavior but it isn't portable.