tags:

views:

175

answers:

2

While reading a binary file using DJGPP on DOS this code hangs. This happens when the fread call is made. If the call is removed then the program runs successfully. The same code runs fine through Visual C++ 2008. Has anyone experienced similar issues with djgpp ? Am I missing out on something really simple ?

char x; 
string Filename = "my.bin" ; 
fp = fopen(Filename.c_str(),"rb"); 

if (fp == NULL)
{
 cout << "File not found" << endl ; 
}

if (fseek (fp, 0, SEEK_END) != 0)
{
    cout <<"End of File can't be seeked"; 
    return -1; 
}

if ( (fileLength = ftell(fp)) == -1)
{
    cout <<"Can't read current position of file"; 
    return -1; 
}

if (fseek (fp, 0, SEEK_SET) != 0)
{
    cout <<"Beginning of File can't be seeked"; 
    return -1; 
} 

if (fread(&x,sizeof(x),1,fp) != sizeof(x))
{
    cout <<"file not read correctly"; 
    return -1; 
}
A: 

fread takes a pointer as the first parameter. If you only have to read in one character, char x; is fine, but pass the address of x instead.

fread(&x,sizeof(x),1,fp) != sizeof(x)

and since sizeof char is always 1 (by definition) you can very well write:

fread(&x,1,1,fp) != 1
dirkgently
fixed that still receive a hang.
vivekian2
+2  A: 
  • I don't see what 'fp' is. I just have to assume it's 'FILE * fp;'.

  • I don't see that you actually include < stdio.h >, and have to assume you do.

  • I don't see that you actually include < iostream > and declare 'using namespace std;', and have to assume you do.

  • I don't see what comes after the fread() call that could tell you if call succeeded.

Going through the process of actually reducing your faulty code to the absolute but complete minimum to reproduce the error is the first thing you should do when a piece of code has you dumbfounded.

It might (and usually does) turn out that the problem isn't even where you thought it is.

That being said, I'd try replacing

if (fread(&x,sizeof(x),1,fp) != sizeof(x))
{
    cout <<"file not read correctly"; 
    return -1; 
}

with

int i;
if ( ( i = fgetc( fp ) ) == EOF )
{
    perror( "File not read correctly" );
    return -1;
}
x = (char) i;
cout << "Success, read '" << x << "'." << endl;

Using 'perror()' instead of homebrewn cout messages gives you additional information on the cause of any error. Using 'fgetc()' will show you that the file actually does contain what you think it does, and that your problems are not due to the somewhat uncommon use of fread() for a single byte.

Then report back.

DevSolar
@DevSolar The problem arose because of something i was doing much prior to this code - switching off some firmware, causing fread() to fail. Your pointed in the right direction though -- "the problem isn't even where you thought it is."
vivekian2