Re: fgets not doing as I expect.



Andrew McMeikan wrote:

I wanted to limit how many chars I read in, but the code below
instead of stopping at 7 chars will happily read 30 or 40 car
lines and spit them out. Not what I expected. Any pointers?

Yes. Start by reading the description of fgets. Then also correct
your postings so that lines do not exceed 72 chars (67 is better).

7.19.7.2 The fgets function
Synopsis
[#1]
#include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);

Description

[#2] The fgets function reads at most one less than the
number of characters specified by n from the stream pointed
to by stream into the array pointed to by s. No additional
characters are read after a new-line character (which is
retained) or after end-of-file. A null character is written
immediately after the last character read into the array.

Returns

[#3] The fgets function returns s if successful. If end-of-
file is encountered and no characters have been read into
the array, the contents of the array remain unchanged and a
null pointer is returned. If a read error occurs during the
operation, the array contents are indeterminate and a null
pointer is returned.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee, Frohe Weihnachten
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
.



Relevant Pages

  • Re: Creating and Accessing Very Big Arrays in C
    ... memory a pointer takes up. ... if I wanted to store a 100x100x100 3D array ... of 'chars', a 1D array would allocate 1,000,000 bytes. ... This allocates 10^6 bytes ...
    (comp.lang.c)
  • Re: Structures with variable length array known at compile time
    ... the array "menu_items" will always have 20 character strings but the ... You have the array the wrong what round -- what you wrote is an array ... of 20 arrays of q characters each. ... One way is to have a pointer to an array. ...
    (comp.lang.c)
  • Re: newbie question
    ... So for an array of 1000 chars, ... converted to a pointer to the first element, that is a pointer to char ... Using the operator is a syntactic sugar for dereferencing the ...
    (comp.lang.c)
  • Re: Bug/Gross InEfficiency in HeathFields fgetline program
    ... It could legally be a pointer to a character array of at least n characters, ... If so, the strlencall will not terminate at the end of the array, so this code would have undefined behavior. ... There's no guarantee in the C standard that it goes into segfault. ...
    (comp.lang.c)
  • Re: difference between string literal declarations
    ... an array of characters. ... The definition for 's' allocates a pointer in addition to the ... storage of the character string "hello, ... 't' only allocates the string characters. ...
    (comp.std.c)