从二进制文件 c++ 读取 16 位整数
Reading 16-bit integers from binary file c++
我不确定我是否做对了,所以我想检查我的代码。 它有效,但我不确定它是否正常工作。我需要它来读取二进制文件,并将 16 位整数存储在所需的确切大小的整数数组中。我试图做sizeof(storage[i])
这样我就可以看看我是否存储了 16 位,但它说 32(我猜是因为 int 自动分配 4 个字节?
void q1run(question q){
int end;
std::string input = q.programInput;
std::ifstream inputFile (input.c_str(), ios::in | ios::binary); //Open File
if(inputFile.good()){ //Make sure file is open before trying to work with it
//Begin Working with information
cout << "In File: t" << input << endl;
inputFile.seekg(0,ios::end);
end=inputFile.tellg();
int numberOfInts=end/2;
int storage[numberOfInts];
inputFile.clear();
inputFile.seekg(0);
int test = 0;
while(inputFile.tellg()!=end){
inputFile.read((char*)&storage[test], sizeof(2));
cout << "Currently at position" << inputFile.tellg() << endl;
test++;
}
for(int i=0;i<numberOfInts;i++){
cout << storage[i] << endl;
}
}else{
cout << "Could not open file!!!" << endl;
}
}
编辑:::::::::::::::::::::::::::::::::::::::::::::;
我将 read 语句更改为:
inputFile.read((char*)&storage[test], sizeof(2));
和要键入的数组 short
. 现在它运行良好,除了输出有点奇怪:
In File: data02b.bin
8
Currently at position4
Currently at position8
10000
10002
10003
0
我不确定.bin文件中有什么,但我猜 0 不应该在那里。 哈哈
用法:int16_t
in <cstdint>
.(保证 16 位(
Short
s 和 int
s 可以具有各种大小,具体取决于体系结构。
是的
,int 是 4 个字节(在 32 位 x86 平台上(。
您有两个问题:
- 正如 Alec Teal 在评论中正确提到的那样,您的存储声明为 int,这意味着 4 个字节。没问题,真的 - 您的数据将适合。
- 实际问题:您正在读取文件的行:
inputFile.read((char*)&storage[test], sizeof(2));
实际上是读取 4 个字节,因为 2 是整数,所以sizeof(2)
是 4。你不需要那里sizeof
。
存储被声明为"int"的"数组",sizeof(int(=4
不过这应该不是问题,您可以在 16 位空间中容纳 32 位值,您可能的意思是short storage[...
此外,为了完全公开,size 根据 sizeof(char( 定义为单调递增序列。
4是迄今为止最常见的,因此假设。(限制.h 将澄清(
存储 16 位整数的一种方法是使用 short
或 unsigned short
类型。
4 的 sizeof(2)
,因为 2 是类型 int
,因此读取 16 的方法是使storage
类型为 short
并读取:
short storage[numberOfInts];
....
inputFile.read((char*)&storage[test], sizeof(short));
您可以在此处找到包含所有类型大小的表格。
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 如何从字符串C++读取多个整数
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何使用字符和整数C 读取文件
- 从文件到短 /长整数读取字节
- do整数读取需要受到关键部分的保护
- 此项目不会将整数读取为二进制并将其作为二进制输出到新文件
- 将连续字节作为一个整数读取
- 如何将文件中的整数读取到动态数组中
- 如何将字符串读取为字符串向量或将整数读取为整数向量
- 将文件中的间隔整数读取到C++数组中
- 将文件中的整数读取到C++中的向量中
- 如何在C++中将空格和换行符分隔的整数读取到2D数组中
- 将一组整数读取为C++中的字符串
- 我如何得到多行字符串和整数读取和输入文件,并在c++中显示
- 通过无符号整数读取无符号字符数组未定义,因此不安全