C++ 将二进制文本读入数组?

C++ 将二进制文本读入数组?,c++,binaryfiles,C++,Binaryfiles,我有一个程序,我需要读入二进制文本。我通过重定向读取二进制文本: readData将是由我的Makefile生成的可执行文件 示例:readData

我有一个程序,我需要读入二进制文本。我通过重定向读取二进制文本:

readData将是由我的Makefile生成的可执行文件

示例:readData 我要做的是读取二进制文本,并将二进制文本文件中的每个字符作为字符存储在字符数组中。二进制文本由32个字符组成这是我的尝试

unsigned char * buffer;
char d;
cin.seekg(0, ios::end);
int length = cin.tellg();
cin.seekg(0, ios::beg);
buffer = new unsigned char [length];
while(cin.get(d))
{
  cin.read((char*)&buffer, length);
  cout << buffer[(int)d] << endl;
}

然而,我在这方面一直有一个细分错误。有人对如何将二进制文本读入字符数组有什么想法吗?谢谢
while(cin.get(&d)){

最简单的方法如下:

std::istringstream iss;
iss << std::cin.rdbuf();

// now use iss.str()
或者,全部放在一行中:

std::string data(static_cast<std::istringstream&>(std::istringstream() << std::cin.rdbuf()).str());

像这样的东西应该能奏效。 从参数中检索文件名,然后一次性读取整个文件

const char *filename = argv[0];
vector<char> buffer;

// open the stream
std::ifstream is(filename);

// determine the file length
is.seekg(0, ios_base::end);
std::size_t size = is.tellg();
is.seekg(0, std::ios_base::beg);

// make sure we have enough memory space
buffer.reserve(size);
buffer.resize(size, 0);

// load the data
is.read((char *) &buffer[0], size);

// close the file
is.close();

然后,您只需在向量上迭代即可读取字符。

出现分段错误的原因是因为您试图使用字符值访问数组变量

问题:

buffer[(int)d] //d is a ASCII character value, and if the value exceeds the array's range, there comes the segfault.
如果您想要的是字符数组,那么您已经从cin.read获得了该数组

解决方案:

cin.read(reinterpret_cast<char*>(buffer), length);

我使用reinterpret_cast是因为它认为转换为有符号字符指针是安全的,因为使用的大多数字符的范围都在0到127之间。您应该知道,从128到255的字符值会被错误地转换。

我说的是二进制文本,因为我不是从二进制文件中读取的。。但是简单地重定向二进制文件中的文本作为输入到我的程序中,二进制和文本通常被用作文件内容的互斥描述。这不是因为你不能将二进制块写入文本文件或将纯文本字符串写入二进制文件,而是因为混合模式很少有用。所以,当你说二进制文本文件或二进制文件中的文本时,我们会抓狂。注意:所有文件都以二进制格式存储,但在文本文件中,所有内容都将被视为文本。
printf("%s", buffer);