c++ - 如何从文件中读取 unsigned short?

标签 c++ c file-io

我有一个正在解析的位图图像,我需要能够打开该文件并存储第一个未签名的短整型。

我尝试使用 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/

相关文章:

c++ - 如何在 C++ 中跟踪 NaN

c - 将数组元素添加到结构中的数组

c - 如何在 OpenGL 中创建便宜的阴影?

c - lua中如何实现接口(interface)?

c++ - 从 Form2 显示 Form1

c++ - 给定这两个值的函数会产生第三个值?

c++ - 检查类型是否可以显式转换

c++ - 为什么将 char 数组复制到结构中时 memcpy 不起作用?

c++ - 使用 GetFileSize 获取文件大小报告有效文件的 segv

python - 如何在 python 程序中处理来自 Windows 的文件切换