我有一个函数,它接收一个指向字符串的指针,该字符串的名称为要打开的文件,并用 1 和 0 进行编码; codedLine 包含类似 010100110101110101010011 的内容 写入二进制文件后,我得到了完全相同的...你会推荐吗?谢谢。
void codeFile(char *s)
{
char *buf = new char[maxStringLength];
std::ifstream fileToCode(s);
std::ofstream codedFile("codedFile.txt", std::ios::binary);
if (!fileToCode.is_open())
return;
while (fileToCode.getline(buf, maxStringLength))
{
std::string codedLine = codeLine(buf);
codedFile.write(codedLine.c_str(), codedLine.size());
}
codedFile.close();
fileToCode.close();
}
最佳答案
After writing to binary file I have exactly the same...
我想你想转换 std::string
输入到它的二进制等价物。
您可以使用 std::bitset<>
类将字符串转换为二进制值,反之亦然。将字符串直接写入文件会导致字符值的二进制表示 '0'
和 '1'
.
一个如何使用它的例子:
std::string zeroes_and_ones = "1011100001111010010";
// Define a bitset that can hold sizeof(unsigned long) bits
std::bitset<sizeof(unsigned long) * 8> bits(zeroes_and_ones);
unsigned long binary_value = bits.to_ulong();
// write the binary value to file
codedFile.write((const char*)&binary_value, sizeof(unsigned long));
注意
以上示例适用于 c++11标准。对于早期版本 std::bitset
不能直接从字符串初始化。但它可以使用 operator>>()
填充和 std::istringstream
例如。
关于c++ - 无法将 1 和 0 的字符串写入二进制文件,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22591429/