C++ 逐个保存无符号字符向量 #包括“stdafx.h” #包括“Compiler.h” #包括 int main(){ 流输出的std::of(“file.bin”,std::ios::binary | std::ios::trunc); if(output.fail()){ 返回1; } std::vector f=运行时::将行转换为指令(“rt\u reg str Hello”); for(无符号字符i:f){ //write(reinterpret_cast&i,sizeof(unsigned short));在这里不起作用。 } 使用output.put(i);,因为它一次只需要一个字符
但您确实想跳过for循环,只需在一次写入中写入整个向量:C++ 逐个保存无符号字符向量 #包括“stdafx.h” #包括“Compiler.h” #包括 int main(){ 流输出的std::of(“file.bin”,std::ios::binary | std::ios::trunc); if(output.fail()){ 返回1; } std::vector f=运行时::将行转换为指令(“rt\u reg str Hello”); for(无符号字符i:f){ //write(reinterpret_cast&i,sizeof(unsigned short));在这里不起作用。 } 使用output.put(i);,因为它一次只需要一个字符,c++,vector,char,unsigned,C++,Vector,Char,Unsigned,但您确实想跳过for循环,只需在一次写入中写入整个向量: #include "stdafx.h" #include "Compiler.h" #include <fstream> int main() { std::ofstream output("file.bin", std::ios::binary | std::ios::trunc); if(output.fail()) { return 1; } std::vector<
#include "stdafx.h"
#include "Compiler.h"
#include <fstream>
int main() {
std::ofstream output("file.bin", std::ios::binary | std::ios::trunc);
if(output.fail()) {
return 1;
}
std::vector<unsigned char> f = Runtime::convert_line_to_instructions("rt_reg str Hello");
for(unsigned char i : f) {
//output.write(reinterpret_cast<char*>&i, sizeof(unsigned short)); doesn't work here.
}
std::cerr << "Program Compiled!" << std::endl;
while(true);
return 0;
}
它是一个fstream,因此您可以使用iostream操作符,比如
如果数据是一个简单的无符号字符数组,您将如何保存数据?sizeof(unsigned short)
为什么用short表示字符的大小?@PaulMcKenzie确实是一样的。你也可以用范围循环来解析数组。output@manni66似乎不起作用。文件大小仍然是0字节。文件大小仍然是0字节。你的程序末尾有一个无限循环,因此你永远不会将输出刷新到文件中。因此,当你中止程序时数据丢失。您的代码不会写入二进制
,即使您使用所列的std::ios::binary
@Brandon打开文件,它确实会写入二进制,我有一个十六进制转储来证明这一点。问题是,如果您弄乱了输出格式,它就不能保证写入二进制数据。如果您不这样做,它就会工作。
output.write(f.data(), f.size());
#include <fstream>
#include <iostream>
#include <vector>
int main(const int argc, const char* argv[]) {
std::ofstream output{"file.bin", std::ios::binary | std::ios::trunc};
if (output.fail())
return 1;
std::vector<unsigned char> input = {'r', 't', '_', 'r', 'e', 'g', ' ',
's', 't', 'r', ' ', 'H', 'e', 'l',
'l', 'o'};
for (const auto i : input)
output << i;
return 0;
}
std::copy(begin(input), end(input), std::ostreambuf_iterator<char>(output));