在DOS上使用DJGPP读取二进制文件时,此代码挂起。当进行fread调用时,就会发生这种情况。如果调用被移除,则程序成功运行。同样的代码在Visual C++ 2008中运行良好。有没有人遇到过djgpp类似的问题?我是不是错过了一些非常简单的东西?
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;
}发布于 2009-03-23 11:51:48
当一段代码让你目瞪口呆时,你应该做的第一件事就是通过实际过程将错误代码减少到绝对但完整的最小化,以重现错误。
它可能(通常确实会)证明问题甚至不是您认为的问题所在。
话虽如此,我还是会试着替换
if (fread(&x,sizeof(x),1,fp) != sizeof(x))
{
cout <<"file not read correctly";
return -1;
}使用
int i;
if ( ( i = fgetc( fp ) ) == EOF )
{
perror( "File not read correctly" );
return -1;
}
x = (char) i;
cout << "Success, read '" << x << "'." << endl;使用'perror()‘代替homebrewn cout消息可以为您提供有关任何错误原因的附加信息。使用'fgetc()‘将显示该文件实际上包含了您认为它所做的事情,并且您的问题并不是由于对单个字节使用了fread()而引起的。
然后再回来报告。
发布于 2009-03-20 17:11:14
fread接受一个指针作为第一个参数。如果只需要读入一个字符,那么char x;也可以,但是要传递x的地址。
fread(&x,sizeof(x),1,fp) != sizeof(x)由于sizeof char始终为1(根据定义),您可以很好地这样写:
fread(&x,1,1,fp) != 1https://stackoverflow.com/questions/667055
复制相似问题