像 python 一样在 C++ 中读取二进制文件
reading a binary file in c++ just like in python
我想在 C++ 中以二进制模式读取文件。最初我使用 python 做同样的事情,当我使用 python 读取同一个文件时,我得到了结果 b'\xe0\xa4\xb5\xe0\xa4\xbe\xe0\xa4\xb9'
,当转换为 INT 时,结果是 224 164 181 224 164 190 224 164 185
,我能够注意所有这些 INT 总是在 [0,255]
.
范围内
我想在 C++ 中做同样的事情,但我无法做到这一点我尝试了很多不同的技巧,但我能得到的最好的方法是 C++ 给出负整数。
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>
#include <stdio.h>
int main()
{
std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
file.seekg(0, std::ios::end);
int size = file.tellg();
char ch;
std::string text;
std::cout << "Size = " << size << std::endl;
file.seekg(0, std::ios::beg);
char x;
file.read((&x), 1);
std::cout << static_cast<int>(x) << std::endl;
return 0;
}
请忽略 #include
我用了很多。
OUTPUT
Size = 9
-32
如评论中所述,这里的问题是 char
默认情况下是有符号的 - 这意味着它采用 [-128, 127]
范围内的值。这是,224 将翻转到负端并变为 -32
。
您应该使用 unsigned char
,这将使范围 [0, 255]
.
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>
#include <stdio.h>
int main()
{
std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
file.seekg(0, std::ios::end);
int size = file.tellg();
unsigned char ch;
std::string text;
std::cout << "Size = " << size << std::endl;
file.seekg(0, std::ios::beg);
unsigned char x;
file.read((&x), 1);
std::cout << static_cast<int>(x) << std::endl;
return 0;
}
我想在 C++ 中以二进制模式读取文件。最初我使用 python 做同样的事情,当我使用 python 读取同一个文件时,我得到了结果 b'\xe0\xa4\xb5\xe0\xa4\xbe\xe0\xa4\xb9'
,当转换为 INT 时,结果是 224 164 181 224 164 190 224 164 185
,我能够注意所有这些 INT 总是在 [0,255]
.
我想在 C++ 中做同样的事情,但我无法做到这一点我尝试了很多不同的技巧,但我能得到的最好的方法是 C++ 给出负整数。
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>
#include <stdio.h>
int main()
{
std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
file.seekg(0, std::ios::end);
int size = file.tellg();
char ch;
std::string text;
std::cout << "Size = " << size << std::endl;
file.seekg(0, std::ios::beg);
char x;
file.read((&x), 1);
std::cout << static_cast<int>(x) << std::endl;
return 0;
}
请忽略 #include
我用了很多。
OUTPUT
Size = 9
-32
如评论中所述,这里的问题是 char
默认情况下是有符号的 - 这意味着它采用 [-128, 127]
范围内的值。这是,224 将翻转到负端并变为 -32
。
您应该使用 unsigned char
,这将使范围 [0, 255]
.
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>
#include <stdio.h>
int main()
{
std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
file.seekg(0, std::ios::end);
int size = file.tellg();
unsigned char ch;
std::string text;
std::cout << "Size = " << size << std::endl;
file.seekg(0, std::ios::beg);
unsigned char x;
file.read((&x), 1);
std::cout << static_cast<int>(x) << std::endl;
return 0;
}