delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/05/06/18:29:02

Date: Sat, 6 May 2000 17:41:43 -0400 (EDT)
Message-Id: <200005062141.RAA07172@indy.delorie.com>
From: Eli Zaretskii <eliz AT delorie DOT com>
To: djgpp AT delorie DOT com
In-reply-to: <l476hs8q4tskk01uq232gj9f30scupjea5@4ax.com> (message from Damian
Yerrick on Fri, 05 May 2000 19:22:02 GMT)
Subject: Re: reading text files
References: <s0ptgsk9052i4lft8hm38o3r0ugjncb64e AT 4ax DOT com> <Pine DOT SUN DOT 3 DOT 91 DOT 1000503115802 DOT 4851L-100000 AT is> <l476hs8q4tskk01uq232gj9f30scupjea5 AT 4ax DOT com>
Reply-To: djgpp AT delorie DOT com
Errors-To: nobody AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

> 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 -


  webmaster     delorie software   privacy  
  Copyright 2019   by DJ Delorie     Updated Jul 2019