NEED HELP: fread, fwrite, fseek, ftell

Steven M. List itkin at mrspoc.UUCP
Tue May 2 10:52:15 AEST 1989


I am trying to write a simple little program to swap bytes and/or words
in a file.  The program works great except for one little problem.  When
I try to do it in place, the file just keeps growing and growing and...

The following fragment is the functional piece of code.  When I've run
it under sdb, I find that when the program should be reading zero bytes
it is still returning 1024 in bytesread.  It then writes out that 1k
chunk and apparently thinks that it's read in another 1k block.  From
what I've been able to tell, the block that it locks in on is the first
block in the file!  That is, it keeps reading and writing the first 1k
block in the file indefinitely.  When I commented out the fseeks and ftells
and changed it to write to stdout (as you see here), it worked great.

This, needless to say, is happening on XENIX 2.3.1 with the 2.2.3 development
system.  I haven't a clue.  fread appears to work properly under all
other circumstances.  I don't appear to be doing anything wrong with the
ftell and fseek calls (I've checked as far as I can in sdb).  Hmmmmm...

Any suggestions?  Please?
------------------------------------------------------------------------------
do_byte_swap (swabfile)
register FILE *swabfile;
{
	extern long ftell ();
	extern int  fseek ();

	long	startpos;

	char	inbuf[1024];
	char	outbuf[1024];

	int	bytesread;
	int	byteswritten;

	register int blocknum = 0;
	register int rc;

	rewind (swabfile);
/* 	startpos = ftell (swabfile); */

	bytesread = fread (inbuf, sizeof (char), sizeof inbuf, swabfile);
	while (bytesread > 0)
	{
		swab (inbuf, outbuf, bytesread);
/* 		if ((rc = fseek (swabfile, startpos, 0)) != 0) */
/* 		{ */
/* 			fprintf (stderr, "file seek error, status = %d\n", rc); */
/* 			exit (1); */
/* 		} */
/*		byteswritten = fwrite (outbuf, sizeof (char), bytesread, swabfile); */
		byteswritten = fwrite (outbuf, sizeof (char), bytesread, stdout);
		if (byteswritten != bytesread)
		{
			fprintf (stderr,
				"swabbit: write error: read %ld bytes, wrote %ld bytes\n",
				bytesread, byteswritten);
			fprintf (stderr,
				"         restore file from backup - probably corrupted!\n");
			exit (1);
		}
/* 		fflush (swabfile); */
/* 		startpos = ftell (swabfile); */
		bytesread = fread (inbuf, sizeof (char), sizeof inbuf, swabfile);
		fprintf (stderr, "%d", ++blocknum);
		if ((blocknum % 70) == 0) fprintf (stderr, "\n");
	}

	fprintf (stderr, "\n");

	return 0;
}
-- 
:  Steven List @ Transact Software, Inc. :^>~
:  Chairman, Unify User Group of Northern California
:  {apple,coherent,limbo,mips,pyramid,ubvax}!mrspoc!itkin
:  Voice: (415) 961-6112



More information about the Comp.unix.xenix mailing list