Turbo C and ^Z's

Otto J. Makela otto at tukki.jyu.fi
Mon Jan 7 17:08:56 AEST 1991


In article <1991Jan04.173903.20643 at dirtydog.ima.isc.com> karl at ima.isc.com (Karl Heuer) writes:
[...]
   Lars is correct.  On a file opened in append-mode, fseek() is only useful
   for reading.  (Though some historical implementations implemented append-
   mode with an initial seek-to-end only, this is not acceptable in ANSI C.)

Yes.  Confirm.  Affirmative.  Now that I've gone thru it, this seems to be
how it works.  I didn't realize ANSI decided to break compatibility with Unix
in such a radical way...

   >I'd like to point out I can't use "r+b", 'cause it'll fail if the file does
   >not exist beforehand.

   Then use "w+b".

Can't do that either, 'cause I don't want to kill the file.  I need both.
Here is the fixed code, if someone finds it useful...
--
#include	<stdio.h>
#include	<fcntl.h>

#ifdef	UNIX
#define	fopena(filename)	fopen(filename,"a")
#else

/*
**	MeSsy-DOS kludge to replace fopen(filename,"at")
*/
FILE *fopena(filename)
char *filename;	{
	FILE *f;

	if(f=fopen(filename,"r+b"))	{
		fseek(f,-1L,SEEK_END);
		while(fgetc(f)==0x1A) fseek(f,-2L,SEEK_CUR);
			/* This is needed to clear stdio buffering */
		fseek(f,ftell(f),SEEK_SET);
		setmode(fileno(f),O_TEXT);
	} else
		f=fopen(filename,"wt");
	return f;
}
#endif

/*
**	Test main program
*/
main(argc,argv)
int argc;
char *argv[];	{
	FILE *f;

	if(argc<2)
		fprintf(stderr,"usage: %s file_to_append_to\n",*argv);
	else if(f=fopena(argv[1]))	{
		fprintf(f,"This is the appended text.\n");
		fclose(f);
	} else
		fprintf(stderr,"%s: could not open %s for append\n",
			*argv,argv[1]);
}
--
   /* * * Otto J. Makela <otto at jyu.fi> * * * * * * * * * * * * * * * * * * */
  /* Phone: +358 41 613 847, BBS: +358 41 211 562 (CCITT, Bell 24/12/300) */
 /* Mail: Kauppakatu 1 B 18, SF-40100 Jyvaskyla, Finland, EUROPE         */
/* * * Computers Rule 01001111 01001011 * * * * * * * * * * * * * * * * */



More information about the Comp.lang.c mailing list