Mail Archives: djgpp/1996/10/12/04:10:23
Alexey Kouzmitch wrote:
>
> I get a weird crash if I try something like:
>
> _file_id1=fgetc(_lib_file);
> or,
> read (_lib_file,_file_id1);
>
> where _libe_file is FILE* and _file_id is an int...
>
> How do I got the best way about reading bytes (or structures) from files
> anyway ???
>
> Thanks ahead! I'll be very grateful for HELP !!!
>
> Alexey Kouzmitch.
Umm... that doesn't look quite right. Here's how I'd go about reading a
series of characters from a file - look at this to see what you're doing
different:
#include <stdio.h>
#define MAX 10000
int main( void )
{
static char data[MAX];
FILE *fp;
int c, i;
if ( ( fp = fopen( "foo.dat", "rb" ) ) == NULL )
{
perror( "foo.dat" );
exit( 1 );
}
for ( i = 0; ( c = fgetc( fp ) ) != EOF && i < MAX; i++ )
data[i] = (char) c;
if ( i == MAX && c != EOF )
printf( "Buffer overflow.\n" );
fclose( fp );
return 0;
}
As far as read() is concerned, you're using it wrong. It takes three
parameters: the file descriptor (an integer), a pointer to a buffer,
and a number of bytes to read. You're trying to pass it a file pointer
and an integer, and there's no way that's going to work. Anyway, if you
are going to use file pointers, you should be using fread() (which takes
a buffer, the size of each item, the number of items, and a file
pointer); here's a sample:
#include <stdio.h>
#define MAX 10000
int main( void )
{
char data[MAX];
FILE *fp;
int r;
if ( ( fp = fopen( "foo.dat", "rb" ) ) == NULL )
{
perror( "foo.dat" );
exit( 1 );
}
r = fread( data, sizeof( *data ), MAX, fp );
fclose( fp );
return 0;
}
I seriously recommend that you look in the libc docs for fgetc(),
fread(), read(), etc., and find a good C book. :)
--
John M. Aldrich <fighteer AT cs DOT com>
* Anything that happens, happens.
* Anything that, in happening, causes something else to happen,
causes something else to happen.
* Anything that, in happening, causes itself to happen again, happens
again.
* It doesn't necessarily do it in chronological order, though.
--- Douglas Adams
- Raw text -