简体   繁体   English

C ++:如何直接写入文件(无ASCII)?

[英]C++: How to write to a file directly (no ASCII)?

I need to write to a file directly (file format/extension doesn't matter). 我需要直接写入文件(文件格式/扩展名无关紧要)。 What I want to be able to do is, eg write A to it, and if I opened the file with a hex editor, it would display A, aka the value 10 in decimal. 我想要做的是,例如,向其中写入A,如果我使用十六进制编辑器打开了文件,它将显示A,也就是十进制的值10。

#include <iostream>
int main()
{
    std::ofstream fout("myfile.ext", std::ios::binary);
    std::ofstream::char_type byte = 10; //or = 0xA
    fout.put(byte);
}

Well, if you write 'A' to the file, I'd expect the hex editor to show 41. 好吧,如果您在文件中写入'A' ,则我希望十六进制编辑器显示41。

But let's say we have an int x = 0xa; 但是,假设我们有一个int x = 0xa; , then the way to write that to a file is: ,那么将其写入文件的方法是:

int x = 0xa;
ofstream out("myfile.txt", ios::out|ios::binary);

out.write((char *)&x, sizeof(x)); 

out.close();

Note that this code isn't highly portable, since size of int and the order of bytes within an integer can change from architecture to architecture. 请注意,此代码不是高度可移植的,因为int大小和整数中字节的顺序可能因体系结构而异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM