C++ 以32位二进制数据c++;
我需要将文件作为二进制数据读入,确保该文件为偶数的32位字(如果需要,我可以添加0的填充字节) 我一直在摆弄ios::binary,但有什么我遗漏的吗?例如:C++ 以32位二进制数据c++;,c++,io,C++,Io,我需要将文件作为二进制数据读入,确保该文件为偶数的32位字(如果需要,我可以添加0的填充字节) 我一直在摆弄ios::binary,但有什么我遗漏的吗?例如: string name1 = "first", name2 = "sec", name3 = "third"; int j = 0, k = 0; ifstream ifs(name1.c_str()); ifs >> j; ifs.close(); 这是我需要利用的东西吗?我对这门语言相当陌生。我能够用与雷米·勒博相似的
string name1 = "first", name2 = "sec", name3 = "third";
int j = 0, k = 0;
ifstream ifs(name1.c_str());
ifs >> j;
ifs.close();
这是我需要利用的东西吗?我对这门语言相当陌生。我能够用与雷米·勒博相似的方法读取32位。此代码与C++03兼容
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();
}
#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("END\n"); break; }
word = 0;
file.read((char*)&word,sizeof(word));
//Do something
printf("%d\n",word);
}
}
#包括
#包括
//代码的其余部分。。。
std::ifstream文件(文件名,std::ifstream::in | std::ifstream::binary | std::ifstream::beg);
int32_t单词;
如果(!文件){
//错误
}否则{
while(file.is_open()){
if(file.eof()){printf(“END\n”);break;}
字=0;
read((char*)&word,sizeof(word));
//做点什么
printf(“%d\n”,word);
}
}
请注意,如果文件的增量不是32,我不会添加填充。如果我添加了该功能,我将更新代码。
是格式化的I/O。您需要read()
(并以二进制模式打开文件!)。对于这种情况,我会诚实地使用C风格的fread
…它没有那么笨重…您缺少的是ios::bin
标志的实际含义。不要假设,而是研究文档。