I am trying to translate
while ((getchar()) != '\n');
into assembly but am finding it difficult.
Asked
Active
Viewed 139 times
1

Strollas
- 45
- 4
-
Making asm code that interoperates with C stdio is hard as it depends on the (unspecified) internal details of how the C std library is implemented. It will be different on different operating systems. – Chris Dodd Jan 30 '23 at 05:40
-
@ChrisDodd The C library has been standard for decades. It's behavior is very well documented. So well documented that the C++ standard itself adopts the C standard. – Something Something Jan 30 '23 at 05:57
-
I'm thinking of just calling my assembly version of scan user input, ecall, again to clear the buffer. – Strollas Jan 30 '23 at 05:59
-
@Nole, the interface and behavior of the library is well-defined, of course, but the details of each implementation vary. When getchar is implemented as a macro, it makes use of those internal details. I think that's what Chris was referring to. – prl Jan 30 '23 at 06:09
-
1@NoleKsum: While the behavior and interface is well documented, the internals are not and differ between systems. Generally a `FILE` will contain a buffer, some pointers, and some flags, but the details are not part of the spec. BSD libc and GNU libc are different and Windows is different again. – Chris Dodd Jan 30 '23 at 06:48
-
2The title mentions "flush" (typical for output streams), the code sample calls `getchar` (typical for input streams); that does not match. It's also unclear what part of the code is giving you trouble. Making a `while` loop? Comparing with newline? Calling `getchar()`? Getting the return value from `getchar()`? Or is your intention to write your own I/O read operation from scratch? Please edit your question to clarify. – Ruud Helderman Jan 30 '23 at 09:49
-
Are you asking how to consume all unread input out to the end of a line? As in [How to clear input buffer in C?](https://stackoverflow.com/q/7898215) (which also checks for EOF). Apparently on some systems, `fseek(stdin,0,SEEK_END);` also works, at least to discard the actual input buffer, not necessarily to read any more bytes that user-space hasn't got from the kernel yet. Or use `scanf("%*[^\n]");`. Or as Steve Summit's answer says, if you need this, that's probably a design problem and you should really try to avoid needing this in the first place. – Peter Cordes Jan 30 '23 at 17:16
-
A compiler can turn any of these into RISC-V asm for you. – Peter Cordes Jan 30 '23 at 17:22
1 Answers
2
You would use something like this:
li s0, 10
again:
call getchar
bne a0, s0,again

Something Something
- 3,999
- 1
- 6
- 21
-
`getchar` is generally a C macro -- to have a function, you need `fgetc` instead, but how to get `stdin` in asm code is not specified -- it may be a macro too. – Chris Dodd Jan 30 '23 at 06:50
-
1`getchar is generally a C macro` - I can see `getchar@@GLIBC_2.2.5` defined on `/lib/x86_64-linux-gnu/libc.so.6` – Something Something Jan 30 '23 at 07:15