*BSD News Article 66767


Return to BSD News archive

Path: euryale.cc.adfa.oz.au!newshost.anu.edu.au!harbinger.cc.monash.edu.au!news.mira.net.au!inquo!in-news.erinet.com!bug.rahul.net!rahul.net!a2i!genmagic!sgigate.sgi.com!imci3!imci4!newsfeed.internetmci.com!news.mathworks.com!uunet!in2.uu.net!EU.net!sun4nl!moacs11!not-for-mail
From: waldi@moacs.indiv.nl.net (Waldi Ravens)
Newsgroups: comp.unix.bsd.misc,alt.unix.wizards,comp.unix.misc
Subject: Re: How to write end of file character into file??!
Date: 26 Apr 1996 02:13:52 +0200
Organization: Private Site, Baarn
Lines: 47
Message-ID: <4lp4g0$dp0@moacs11.moacs.indiv.nl.net>
References: <xsvarshney-0604962038290001@newshub.csu.net> <4l5le1$amd@is05.micron.net> <4l85m7$fjs@sv024.SanDiegoCA.ATTGIS.COM> <4lg9i8$8if@is05.micron.net>
NNTP-Posting-Host: moacs11.moacs.indiv.nl.net
Xref: euryale.cc.adfa.oz.au comp.unix.bsd.misc:824 alt.unix.wizards:3709 comp.unix.misc:22185

Dwight Tovey <dwight@micron.net> wrote:
>
> However the following code will go to the "real" end of the file for both
> binary and text files:
> 
> 	char ch;
> 	FILE *fp
> 
> 	fp = fopen( "foo", "r" );
> 	while( !feof( fp )) {
> 		ch = fgetc(fp);
> 		putchar( ch );
> 	}

Sorry, it won't. Two mistakes (apart from the obvious syntax error):
1) assuming an ideal world without I/O errors.
2) confusing C with Ada (or Pascal).

Corrected version:

	char *fn = "foo";
	FILE *fp = fopen(fn, "r");

	while (1) {
		char ch = fgetc(fp);

		if (ferror(fp))
			err(EXIT_FAILURE, "%s", fn);
		if (feof(fp))
			break;
		putchar(ch);
	}

Of course, that looks rather complicated and inefficient compared to:

	int  ch;

	while ((ch = fgetc(fp)) != EOF)
		putchar(ch);
	if (ferror(fp))
		err(EXIT_FAILURE, "%s", fn);


Regards,
Waldi
-- 
Never let your schooling interfere with your education.