C ++编写int缓冲区 [英] C++ writing int buffer
问题描述
我试图写一个int数组到fstream,但是当我调用 fstream.write
时会遇到异常。
I am trying to write an int array to a fstream, but I am getting an exception when I call fstream.write
.
我可以使用 fstream
将一个int数组写入文件吗?
Can I use fstream
to write an int array to a file?
int main(int argc, char * argv[])
{
fstream amostra("D:\\Amostra.txt", ios::out | ios::binary);
const int total_elements_block = 1024;
const int buffer_size = total_elements_block;
const int total_buffer = 10;
int * buffer = new int [buffer_size];
//for (int j=0; j<total_buffer; j++){
for (int i =0; i<total_elements_block; i++){
buffer[i] = i;
}
amostra.write((char *)(&buffer), total_elements_block*4);
//}
amostra.close();
delete []buffer;
return 0;
}
推荐答案
Obvlious
你可以按照他的建议使用(char *)(buffer)
You can do as he suggests and use (char *)(buffer)
, but I disagree with this stylistically.
首先,它使用C风格的转换,这在C ++代码中应该避免。这将略微改进版本 reinterpret_cast< char *>(buffer)
。这将确保你不做任何愚蠢的像删除 const
。
First off, it uses a C-style cast, which should be avoided in C++ code. That would make a slightly improved version be reinterpret_cast<char *>(buffer)
. This will ensure you don't do anything silly like remove const
.
但是,我觉得你可以做略好于那。在某些时候,你可能会认为一个平面数组不会为你工作。也许你想改为C ++ 11 std :: array
或者 std :: vector
。突然你的代码不工作。平面C风格数组是我最常改变的数据类型。因此,您可以考虑看起来更像 reinterpret_cast< char *>(& buffer [0])
的东西。
However, I feel that you can do slightly better than that. At some point, you may decide that a plain array will not work for you. Maybe you want to change to a C++11 std::array
, or a std::vector
. Suddenly your code won't work. A plain C-style array is the data type I change most often. For this reason, you may want to consider something that looks more like reinterpret_cast<char *>(& buffer[0])
.
另请注意,您的代码不可移植。 int
在内存中的布局方式是实现定义的。查看诸如在C ++程序中以编程方式检测字幕顺序的解答
Also note that your code is not portable. The way that an int
is laid out in memory is implementation defined. Look at answers such as Detecting endianness programmatically in a C++ program
这篇关于C ++编写int缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!