delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/05/19/17:05:14

From: zvrba AT jagor DOT srce DOT hr (Zeljko Vrba)
Newsgroups: comp.os.msdos.djgpp
Subject: fscanf bug
Date: 19 May 1997 13:06:37 GMT
Organization: Public host at University Computing Centre, Zagreb, CROATIA
Lines: 51
Distribution: world
Message-ID: <5lpj8t$d37@bagan.srce.hr>
NNTP-Posting-Host: jagor.srce.hr
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

I think that there's a bug in fscanf function:

#include <stdio.h>

void main(void)
{
FILE *f;
int a,b;
char c;

	f=fopen("in.dat", "r");
	while(!feof(f))
	{
		while((c=fgetc(f))!=EOF)
		{
			ungetc(c, f);
			a=fscanf(f, "%d%[\n]", &b, &c); <--------- CRITICAL!
			printf("%d ", b);
			if(a==2)
				break;
		}
		printf("\n");
	}
	fclose(f);
	printf("\n");
}

This program should read numbers from a text file line by line and display
them on screen. Input file:

----------- IN.DAT
1 3 4 5 4 6
32 4 5 -10 12
----------- EOF

This is what DJGPP compiled code outputs:
----------- DJGPP output
1 3 4 5 4 0
32 4 5 -10 10
----------- EOF

and this is what Watcom compiled code outputs:
----------- WATCOM output
1 3 4 5 4 6
32 4 5 -10 12
-----------

I think that Watcom's behaviour is correct.
Why does fscanf incorrectly read the last byte before \n as 0?

- Raw text -


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