Lines 3730-3747
input with a comprehensible error message, not with a crash.
Link Here
|
3730 |
@node Dynamic String Input |
3730 |
@node Dynamic String Input |
3731 |
@subsection Dynamically Allocating String Conversions |
3731 |
@subsection Dynamically Allocating String Conversions |
3732 |
|
3732 |
|
3733 |
A GNU extension to formatted input lets you safely read a string with no |
3733 |
A GNU and POSIX.1-2008 extension to formatted input lets you safely |
3734 |
maximum size. Using this feature, you don't supply a buffer; instead, |
3734 |
read a string with no maximum size. Using this feature, you don't |
3735 |
@code{scanf} allocates a buffer big enough to hold the data and gives |
3735 |
supply a buffer; instead, @code{scanf} allocates a buffer big enough |
3736 |
you its address. To use this feature, write @samp{a} as a flag |
3736 |
to hold the data and gives you its address. To use this feature, |
3737 |
character, as in @samp{%as} or @samp{%a[0-9a-z]}. |
3737 |
write @samp{m} as a flag character, as in @samp{%ms} or |
|
|
3738 |
@samp{%m[0-9a-z]}. |
3738 |
|
3739 |
|
3739 |
The pointer argument you supply for where to store the input should have |
3740 |
The pointer argument you supply for where to store the input should have |
3740 |
type @code{char **}. The @code{scanf} function allocates a buffer and |
3741 |
type @code{char **}. The @code{scanf} function allocates a buffer and |
3741 |
stores its address in the word that the argument points to. You should |
3742 |
stores its address in the word that the argument points to. You should |
3742 |
free the buffer with @code{free} when you no longer need it. |
3743 |
free the buffer with @code{free} when you no longer need it. |
3743 |
|
3744 |
|
3744 |
Here is an example of using the @samp{a} flag with the @samp{%[@dots{}]} |
3745 |
Here is an example of using the @samp{m} flag with the @samp{%[@dots{}]} |
3745 |
conversion specification to read a ``variable assignment'' of the form |
3746 |
conversion specification to read a ``variable assignment'' of the form |
3746 |
@samp{@var{variable} = @var{value}}. |
3747 |
@samp{@var{variable} = @var{value}}. |
3747 |
|
3748 |
|
Lines 3749-3755
conversion specification to read a ``variable assignment'' of the form
Link Here
|
3749 |
@{ |
3750 |
@{ |
3750 |
char *variable, *value; |
3751 |
char *variable, *value; |
3751 |
|
3752 |
|
3752 |
if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n", |
3753 |
if (2 > scanf ("%m[a-zA-Z0-9] = %m[^\n]\n", |
3753 |
&variable, &value)) |
3754 |
&variable, &value)) |
3754 |
@{ |
3755 |
@{ |
3755 |
invalid_input_error (); |
3756 |
invalid_input_error (); |
3756 |
- |
|
|