I'm trying to open a file and put everything before the EOF into a char*. This code crashes, but i don't know enough about memset and malloc etc. to tell what's wrong.
Thanks In Advance.
James
[code]
[blue]#include[/blue]
[blue]#include[/blue]
[blue]#include[/blue]
[blue]int[/blue] main()
{
FILE* f = fopen( "file.name", "rt" );
[blue]char[/blue]* fileStr =0;
[blue]long[/blue] hFile;
[blue]long[/blue] lenFile;
[blue]if[/blue]( f )
{
hFile = _fileno( f );
lenFile = _filelength( hFile );
printf( "the length of Gal.ini is %i bytes
", lenFile );
[green]// The crash occurs on both these lines no matter
//which i comment out.[/green]
memset( fileStr, 0, sizeof( [blue]char[/blue] ) * lenFile);
fread( fileStr, sizeof( [blue]char[/blue] ), lenFile, f );
printf( "the file contains..." );
printf( fileStr );
}
else
{
printf( "problem opening file." );
}
[blue]return[/blue] 0;
}
[/code]
Comments
:
: Thanks In Advance.
:
: James
:
: [code]
: [blue]#include[/blue]
: [blue]#include[/blue]
: [blue]#include[/blue]
:
: [blue]int[/blue] main()
: {
:
: FILE* f = fopen( "file.name", "rt" );
: [blue]char[/blue]* fileStr =0;
: [blue]long[/blue] hFile;
: [blue]long[/blue] lenFile;
:
: [blue]if[/blue]( f )
: {
:
: hFile = _fileno( f );
: lenFile = _filelength( hFile );
:
: printf( "the length of Gal.ini is %i bytes
", lenFile );
: [green]// The crash occurs on both these lines no matter
: //which i comment out.[/green]
: memset( fileStr, 0, sizeof( [blue]char[/blue] ) * lenFile);
: fread( fileStr, sizeof( [blue]char[/blue] ), lenFile, f );
:
: printf( "the file contains..." );
: printf( fileStr );
: }
: else
: {
: printf( "problem opening file." );
: }
:
: [blue]return[/blue] 0;
: }
: [/code]
:
the reason it crashes is that you don't allocate any memory for the data you want to read;
fileStr=0 so when you do "memset( fileStr, 0, sizeof( [blue]char[/blue] ) * lenFile);" you write zeros at the begining of memory =>crash
solution:
before memset: "fileStr=(char *)malloc(sizeof(char)*lenFile);"
Thanks for your help.
James
:
: Thanks for your help.
:
: James
:
that's right