读取文件为32位二进制数据c++
Read file in as 32 bit binary data c++
我需要将文件读取为二进制数据,确保文件是32位字的偶数(如果需要,我可以添加0填充字节)。
我已经摆弄了ios::二进制,但有什么我错过了?例如:
string name1 = "first", name2 = "sec", name3 = "third";
int j = 0, k = 0;
ifstream ifs(name1.c_str());
ifs >> j;
ifs.close();
这是我需要利用的东西吗?我对这门语言相当陌生
std::ifstream ifs(name1.c_str(), std::ifstream::binary);
if (!ifs)
{
// error opening file
}
else
{
int32_t j;
do
{
j = 0;
ifs.read(&j, sizeof(j));
if (ifs)
{
// read OK, use j as needed
}
else
{
if (ifs.eof())
{
// EOF reached, use j padded as needed
}
else
{
// error reading from file
}
break;
}
}
while (true);
ifs.close();
}
我能够使用与Remy Lebeau类似的方法读取32位。此代码与c++ 03兼容。
#include <stdint.h>
#include <fstream>
// Rest of code...
std::ifstream file(fileName, std::ifstream::in | std::ifstream::binary | std::ifstream::beg);
int32_t word;
if(!file){
//error
} else {
while(file.is_open()){
if(file.eof()){ printf("ENDn"); break; }
word = 0;
file.read((char*)&word,sizeof(word));
//Do something
printf("%dn",word);
}
}
注意,如果文件的增量不是精确的32,我不会添加填充。如果我添加了这个功能,我将更新代码。
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 在运行时处理类型擦除的数据-如何不重新发明轮子