Open A File, Read Everything

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

  • : 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]
    :
    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);"

  • in that case do i need memset? if fread will set the data to what's in the file it seems pointless to set it to 0's before that.

    Thanks for your help.

    James
  • : in that case do i need memset? if fread will set the data to what's in the file it seems pointless to set it to 0's before that.
    :
    : Thanks for your help.
    :
    : James
    :
    that's right
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories