I want to implement scanf function using read system call, but I have a problem - when you use read you have to specify how many bits it will read, and I am not sure what number to use. I have for example implemented flag %b
for binary numbers, %x
for hex etc, should I just use a constant amount of bits like 256
?
You will probably have to implement a buffering layer. When you call read()
, you get a number of bytes from the stream. From the point of view of the system, those bytes are now gone and will not be returned by a subsequent call to read()
. The problem is, if you have a format specifier like %d
, you can't know when you are done reading the number until you actually read the next non-digit byte. You'll have to store that already-read input somewhere so you can use it later, for example for a following %s
.
基本上,您必须自己进行缓冲,因为您选择的任何数字在某些情况下可能太大(除非您选择的东西小得可笑),而在其他情况下可能太小(例如, 很多空白),所以没有权利数。
read()
, without a layer of buffering code, will not work to implement scanf()
as scanf()
needs the ability to "unget" characters back to stdin
.
Instead, scanf()
could be implemented with fgetc()/unget()
, but it is a great deal to implement a complete scanf()
, no matter what route is taken.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.