Re: fread() bug?
Re: fread() bug?
- Subject: Re: fread() bug?
- From: Steve Checkoway <email@hidden>
- Date: Sat, 5 Jan 2008 09:59:40 -0800
On Jan 5, 2008, at 8:29 AM, Norm Green wrote:
I've found what I consider to be a stream IO bug. Here's what's
happening:
[snip]
Is this is a bug? Are there any work arounds?
I wouldn't think this is a bug. Stream IO is buffered. Just because
you flushed the output doesn't mean you flushed the input. I would
expect it to read from its buffer. Try fpurge(3). It seems to be a BSD
function, though.
I wrote a simple test case to demonstrate this problem, which passes
on
Solaris.
Something like this?
steve$ cat write.c
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#define STR(x) XSTR(x)
#define XSTR(x) #x
#define ASSERT( x ) \
do { if( !(x) ) { perror( STR(__LINE__) ": " #x ); exit( 1 ); } }
while( 0 )
int main( int argc, const char **argv )
{
FILE *w = fopen( "foo", "w" );
ASSERT( w );
int32_t num = 0xAABBCCDD;
ASSERT( fwrite(&num, 4, 1, w) == 1 );
ASSERT( fflush(w) == 0 );
FILE *r = fopen( "foo", "r" );
ASSERT( r );
ASSERT( fread(&num, 4, 1, r) == 1 );
ASSERT( num == 0xAABBCCDD );
ASSERT( fseek(w, 0, SEEK_SET) == 0 );
num = 0x11223344;
ASSERT( fwrite(&num, 1, 1, w) == 1 );
ASSERT( fflush(w) == 0 );
if( argc > 1 )
ASSERT( fpurge(r) == 0 );
ASSERT( fseek(r, 0, SEEK_SET) == 0 );
ASSERT( fread(&num, 1, 1, r) == 1 );
printf( "%#x\n", num );
ASSERT( num == 0x11223344 );
ASSERT( fclose(r) == 0 );
ASSERT( fclose(w) == 0 );
return 0;
}
steve$ gcc -Wall write.c
steve$ ./a.out
0xaa223344
31: num == 0x11223344: Undefined error: 0
steve$ ./a.out foo
0x11223344
fpurge(3) seems to advance the file pointer so you have to seek after
you purge.
--
Steve Checkoway
"Anyone who says that the solution is to educate the users
hasn't ever met an actual user." -- Bruce Schneier
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden