[OCLUG] Re: [OCLUG-devel] Trouble with strings and files

Christopher Smith x at xman.org
Wed Jul 7 22:46:30 PDT 2004


On Wed, 2004-07-07 at 22:11, Jack Denman wrote:
> On Tuesday 06 July 2004 10:19 pm, Christopher Smith wrote:
> > On Tue, 2004-07-06 at 21:36, James Colannino wrote:
> > > I was wrong.  I should not have used EOF, but instead, should have used
> > > NULL.  The program didn't work until I made that change.  C is fun... :)
> >
> > Hehe. Good on you for figuring that out! I was about to point that one
> > out to you.
> >
> > I'd also personally recommend changing your core logic to this:
> >
> > while (fgets(line, sizeof(line), in_file)) {
> >     FILE* target = div_file;
> >     int number = atoi(line);
> >     if ((number % 3) != 0) { /* != 0 is gratuitous, but clearer */
> >       target = other_file;
> >     }
> >     fputs(line, target);
> > }
> >
> > A number of advantages to this approach:
> >
> 
> fgets should not be used because of buffer overflow, a security violation and 
> the gcc compiler warns about that. The GNU way is as follows:

Not sure how this ended up traveling back on to the main list.

Yes, fgets in general is not a safe function, but James is trying to
write his first couple of programs in C, he is still learning how to
heap allocations work. Give him a chance to learn how C works first, so
he can understand why he can't use fgets (I was hesitant to even
introduce atoi(), but given that scanf is more complex than atoi(), it
was probably a good idea)! Of course, even if we used the getline
function you describe, we'd have other problems to worry about.

-- 
Christopher Smith <x at xman.org>


More information about the OCLUG-devel mailing list