What is the simplest way to read a full line in a C console program The text entered might have a variable length and we can't make any assumption about its content.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
A very simple but unsafe implementation to read line for static allocation:
A safer implementation, without the possibility of buffer overflow, but with the possibility of not reading the whole line, is:
Not the 'difference by one' between the length specified declaring the variable and the length specified in the format string. It is a historical artefact.
On BSD systems and Android you can also use
fgetln
:Like so:
The
line
is not null terminated and contains\n
(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream.You might need to use a character by character (getc()) loop to ensure you have no buffer overflows and don't truncate the input.
Building your own function, is one of the way that would help you to achieve reading a line from console in C.
I'm using dynamic memory allocation to allocate just the sufficient amount of memory required to hold all the characters of a line along with the
'\0'
character.And here I'm using a loop to scan each character of the string one by one using the
getchar()
function untill the user enters'\n'
orEOF
characterNow you could read a full line this way :
Here's an example program using the
scan_line()
function :sample input :
sample output :
getline
runnable exampleMentioned on this answer but here is an example.
It is POSIX 7, allocates memory for us, and reuses the allocated buffer on a loop nicely.
Pointer newbs, read this: Why is the first argument of getline a pointer to pointer "char**" instead of "char*"?
glibc implementation
No POSIX? Maybe you want to look at the glibc 2.23 implementation.
It resolves to
getdelim
, which is a simple POSIX superset ofgetline
with an arbitrary line terminator.It doubles the allocated memory whenever increase is needed, and looks thread-safe.
It requires some macro expansion, but you're unlikely to do much better.
So, if you were looking for command arguments, take a look at Tim's answer. If you just want to read a line from console:
Yes, it is not secure, you can do buffer overrun, it does not check for end of file, it does not support encodings and a lot of other stuff. Actually I didn't even think whether it did ANY of this stuff. I agree I kinda screwed up :) But...when I see a question like "How to read a line from the console in C?", I assume a person needs something simple, like gets() and not 100 lines of code like above. Actually, I think, if you try to write those 100 lines of code in reality, you would do many more mistakes, than you would have done had you chosen gets ;)