Date: Sat, 6 May 2000 17:41:43 -0400 (EDT) Message-Id: <200005062141.RAA07172@indy.delorie.com> From: Eli Zaretskii To: djgpp AT delorie DOT com In-reply-to: (message from Damian Yerrick on Fri, 05 May 2000 19:22:02 GMT) Subject: Re: reading text files References: 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 Precedence: bulk > From: Damian Yerrick > 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).