我有一个正在解析的位图图像,我需要能够打开该文件并存储第一个未签名的短整型。
我尝试使用 FILE 和 fscanf() 来完成此操作,但 fscanf() 总是失败并返回 0(成功读取的项目数)。
FILE *pFile = fopen ( fileName->c_str() , "r" );
if ( pFile == NULL )
{
cerr << "couldn't open file ; exiting..." << endl;
exit(0);
}
unsigned short seed;
fscanf (pFile, "%hu", &seed);
有谁知道我可以采用的另一种方法(可能是 ifstream?)或者可以给我一些指示吗?任何帮助将不胜感激。
谢谢。
最佳答案
不要使用像*scanf这样的格式化函数;他们期望数据的字符表示,*printf 函数的补充,将值转换为字符表示。
unsigned val;
f = fopen (filename, "rb");
if (fread (&val, 1, sizeof (val), f) != sizeof (val))
// error
最大的警告是文件的写入方式。如果 writer 的字节序与运行它的计算机不同,那么应该使用显式的字节序代码:
unsigned val;
unsigned char buf[2];
f = fopen (filename, "rb");
if (fread (buf, 1, sizeof (buf), f) != sizeof (buf))
// error
else {
// val = (buf [0] << 8) | buf [1]; // for big endian written file
val = (buf [1] << 8) | buf [0]; // for little endian written file
}
关于c++ - 如何从文件中读取 unsigned short?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1780876/