L
Luo Yong
Hi all
Is there anyway to control the maxium length of the IO.readline can read?
Thanks
Is there anyway to control the maxium length of the IO.readline can read?
Thanks
Not really, not from the command line. You can throw away all the length you
don't want once it has been entered. It is way better to expect more
characters than you get than to get more than you expect (long sad story
about C/C++ "gets" snipped here).
Maybe you should describe the problem, rather than asking about this way of
solving it.
As written, "readline" won't read more than it can safely store, which is
what you are after. Your concern arose from such things as "gets",
mentioned in my last post, that wrote beyond its allocated buffer because
it didn't know its length.
Why don't you read a character at a time, then stop reading characters after
you have what you want? Like this:
-----------------------------------
#!/usr/bin/ruby -w
max = 16
while true
print "Type something:"
STDOUT.flush
input = STDIN.sysread(max)
puts "\nYou entered (in chunks of #{max} chars) #{input}."
end
-----------------------------------
This routine reads the input in chunks of "max" characters, and continues to
cycle through similarly sized chunks indefinitely. Linefeeds are not
special to it, although that would be easy to add. This gives you a limit
on input size, but you then have to sort out for yourself what a line is,
and where one ends and another begins.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.