我想将我的文件表示为一个字符串,但我有一个问题,该文件包含一个 0x00 并且我的字符串在那里被终止。如何解决这个问题?
问问题
864 次
3 回答
1
如果您不能使用 null 作为终止字符,那么您只有很少的选择:
a) 在字符串之前写入字符串大小:005Hello 011Hello\0World
b) 使用固定长度的字符串
c) 在非终止空值前面加上一个特殊的字符,如 '\'。如果 '\' 出现在您的字符串中,请将其写入两次“\”。回读它们时颠倒逻辑。
于 2013-08-17T06:03:22.917 回答
1
我在二进制 0x61 0x61 0x61 0x00 0x62 0x62 0x62 中有一个这样的 txt 文件
二进制“txt文件”?- 我不知道这是什么意思。
但是,如果您有用空格分隔的值,您可以尝试使用std::vector
of std::string
(不使用空终止)
std::ifstream fin("input.txt");
std::vector<std::string> v;
std::copy(std::istream_iterator<std::string> (fin),
std::istream_iterator<std::string> (),
std::back_inserter(v) );
std::vector<std::string>::iterator it =v.begin();
for(;it!=v.end();++it)
std::cout<< *it<<" ";
于 2013-08-17T06:06:58.180 回答
0
确保以二进制模式读取文件:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
std::string read_file_as_string(const char* filename) {
std::ifstream input(filename, std::ios::binary);
if (!input) {
std::perror("Great failure");
std::exit(1);
}
std::stringstream contents;
contents << input.rdbuf();
return contents.str();
}
int main() {
std::string s = read_file_as_string("Derp.exe");
std::cout << "s.size() = " << s.size() << '\n';
for(unsigned char c : s) {
std::cout << std::hex << static_cast<unsigned int>(c) << ' ';
}
std::cout << '\n';
}
于 2013-08-17T06:13:13.103 回答