On Fri, 7 Sep 2007, Magnus Myrefors wrote:

> By the way I have found out that I used a way of reading lines 
> from the input-file which can cause some problem. I read in a 
> book that fgets(string, sizeof(string), input) should read one 
> line up to sizeof(string) -1 or to the first newline- character. 
> But when I tested I found out that that wasn't the case. That 
> can explain the false data.

Well, "explain" in some sense, I suppose.  If fgets is not 
behaving on your system as the ISO C standard says it should, all 
bets are off.  

However, are you sure you have interpreted this correctly?  The 
"sizeof" business in particular.  Let's suppose you have a valid 
FILE *, fp, from which to read.

(1) correct:

char line[1024];
while (fgets(line, sizeof line, fp)) {
   /* do stuff */
}

(2) wrong:

char *line = malloc(1024);
while (fgets(line, sizeof line, fp)) {
   /* do stuff */
}

In case (1) sizeof line is 1024, while in case (2) sizeof line is 
the size of a char * pointer on your system, which is likely 4 
bytes (maybe 8). If your read buffer is allocated dynamically you 
need to do something like

(3) correct:

int buflen = 1024;
char *line = malloc(buflen);
while (fgets(line, buflen, fp)) {
   /* do stuff */
}

Allin Cottrell
_______________________________________________
gtk-app-devel-list mailing list
gtk-app-devel-list@gnome.org
http://mail.gnome.org/mailman/listinfo/gtk-app-devel-list

Reply via email to