Mail Archives: djgpp/2000/05/06/18:29:02
> From: Damian Yerrick <Bullcr_pd_yerrick AT hotmail DOT comRemoveBullcr_p>
> Date: Fri, 05 May 2000 19:22:02 GMT
>
> int main(void)
> {
> char foo[16];
> FILE *fp = fopen("foo.txt", "rb");
>
> if(!fp)
> {
> puts("couldn't open foo.txt for writing.\n"
> "It should contain one line with one very long word.");
> return 1;
> }
> fscanf(fp, "%s", foo);
> printf("read word: %s\n", foo);
> return 0;
If you replace fscanf with fgets+sscanf in this case, without changing
the format or anything else, it will blow up the stack in exactly the
same way. Did you try it?
> sscanf() knows that no incoming string will be longer than the input
> string.
Sorry, I cannot parse this statement. Care to explain?
In general, `sscanf' works the same as the other *scanf functions,
because they all rely on common code inside the function `_doscan',
which doesn't know anything about who called it.
Also, the reason for the crash in the program you posted is that the
buffer foo[] is too small to accept the input from the file. `sscanf'
cannot solve this problem, since it doesn't know how large is its
third argument. It only knows how large is its first argument.
Finally, there should be no reason to use `fscanf' to read a string
with "%s" format. `fscanf' is for converting text into non-text data,
and when used as such, `sscanf' and `fscanf' behave even closer
(i.e. blow or not in the same way).
- Raw text -