将二进制文本读入数组?

时间:2012-12-03 00:52:22

标签: c++ binaryfiles

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

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

示例:readData< binaryText.txt

我想要做的是读取二进制文本,并将二进制文本文件中的每个字符存储为char数组中的字符。二进制文本由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;
}

但是,我不断收到分段错误。任何人都有任何关于如何将二进制文本读入char数组的想法?谢谢!

4 个答案:

答案 0 :(得分:0)

我更像是一个C程序员而不是C ++,但我认为你应该已经启动了你的while循环

while(cin.get(&d)){

答案 1 :(得分:0)

最简单的就是这样:

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

// now use iss.str()

或者,全部在一行:

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

答案 2 :(得分:0)

这样的事情应该可以解决问题。 您从参数中检索文件名,然后一次性读取整个文件。

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();

然后你需要迭代vector来读取字符。

答案 3 :(得分:0)

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

问题:

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);

如果要打印,只需使用printf

printf("%s", buffer);

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

相关问题