[英]Cannot Read Binary files in byte mode in C++
我試圖讀取二進制文件的數據,可悲的是,在C ++中打開這些文件與在python中有很多區別,因為它們具有字節模式。 看來C ++沒有。
for (auto p = directory_iterator(path); p != directory_iterator(); p++) {
if (!is_directory(p->path()))
byte tmpdata;
std::ifstream tmpreader;
tmpreader.open(desfile, std::ios_base::binary);
int currentByte = tmpreader.get();
while (currentByte >= 0)
{
//std::cout << "Does this get Called?" << std::endl;
int currentByte = tmpreader.get();
tmpdata = currentByte;
}
tmpreader.close()
}
else
{
continue;
}
我基本上想要克隆Python在'rb'
模式下打開文件的方法。 必須具有所有內容的實際字節數據(這是不可讀的,因為即使對於C ++,它也具有不可打印的字符。其中大多數可能僅由於包含zlib壓縮數據而無法轉換為帶符號的字符,我需要將其輸入DLL解壓縮所有內容。
我確實知道在Python中我可以做這樣的事情:
file_object = open('[file here]', 'rb')
事實證明,以此替換上面的C ++代碼會有所幫助。 但是fopen
已貶值,但我不在乎。
上面的代碼沒有做的是工作,因為我沒有從緩沖區數據中讀取。 后來我才意識到, fopen
, fseek
, fread
和fclose
是讀取字節模式('rb')所需的功能。
for (auto p = directory_iterator(path); p != directory_iterator(); p++) {
if (!is_directory(p->path()))
{
std::string desfile = p->path().filename().string();
byte tmpdata;
unsigned char* data2;
FILE *fp = fopen("data.d", "rb");
fseek(fp, 0, SEEK_END); // GO TO END OF FILE
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET); // GO BACK TO START
data2 = new unsigned char[size];
tmpdata = fread(data2, 1, size, fp);
fclose(fp);
}
else
{
continue;
}
int currentByte = tmpreader.get();
while (currentByte >= 0)
{
//std::cout << "Does this get Called?" << std::endl;
int currentByte = tmpreader.get();
//^ here!
您正在聲明隱藏外部變量的第二個變量。 但是,此內部變量僅在while循環的主體內有效,因此while條件檢查不再修改的外部變量。 而是這樣做:
int currentByte;
while ((currentByte = tmpreader.get()) >= 0)
{
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.