C++ C++;二进制文件到结构
我正试图从二进制文件中读取一些数据 我的结构设置如下所示:C++ C++;二进制文件到结构,c++,struct,binary,ifstream,C++,Struct,Binary,Ifstream,我正试图从二进制文件中读取一些数据 我的结构设置如下所示: struct track{ unsigned long ID; string title; }; #include <cstdint> #include <fstream> #include <string> struct track { uint32_t id; c
struct track{
unsigned long ID;
string title;
};
#include <cstdint>
#include <fstream>
#include <string>
struct track { uint32_t id; char title[8]; };
std::ifstream infile("thefile.bin");
for (;;)
{
track t;
if (!infile.read(reinterpret_cast<char*>(&t.id), 4) ||
!infile.read(t.title, 8) ||
infile.gcount() != 8)
{
// error, die (or perhaps end of file)
}
// now you can use "t", e.g.:
std::string title(t.title, 8); // a sane string object
}
以及一个存储值的文件,如
[00000001][5468652054726163]
[00000002][6F776C6F6F6B6174]
这是我用伪代码编写的糟糕逻辑
blocksize = 4; // Read 4 bytes at a time
while(!endoffile){
track[i].ID = (blocksize,pos) // get 4 bytes starting at position
track[i].title = blocksize*2,pos+4) // get 8 bytes starting 4 after last position
pos+12; i++;
}
对不起,太糟糕了。就像我说的,我是C++新手。我知道如何使用fstream等,只是在二进制中循环使用字节的逻辑让我完全发疯了 您可以这样做:
struct track{
unsigned long ID;
string title;
};
#include <cstdint>
#include <fstream>
#include <string>
struct track { uint32_t id; char title[8]; };
std::ifstream infile("thefile.bin");
for (;;)
{
track t;
if (!infile.read(reinterpret_cast<char*>(&t.id), 4) ||
!infile.read(t.title, 8) ||
infile.gcount() != 8)
{
// error, die (or perhaps end of file)
}
// now you can use "t", e.g.:
std::string title(t.title, 8); // a sane string object
}
#包括
#包括
#包括
结构跟踪{uint32_t id;字符标题[8];};
标准::ifstream infle(“thefile.bin”);
对于(;;)
{
轨道t;
如果(!infle.read(重新解释铸件(&t.id)),4)||
!infle.read(t.title,8)||
infle.gcount()!=8)
{
//错误、死亡(或文件结尾)
}
//现在您可以使用“t”,例如:
std::string title(t.title,8);//一个正常的字符串对象
}
您应该在c++11中包含stdint.h
(或cstdint
),以便使用uint32\u t
类型。嗨@BillyJakeOConnor!如果这个或任何答案已经解决了你的问题,请考虑点击复选标记。这向更广泛的社区表明,你已经找到了一个解决方案,并给回答者和你自己带来了一些声誉。没有义务这样做。:)@0x499602D2当时我无法接受,完全忘记了。谢谢你提醒我。