问题
I am trying to write an int array to a fstream, but I am getting an exception when I call fstream.write
.
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;
}
回答1:
Captain Obvlious is correct in diagnosing your problem, however, there are really a few possible fixes here.
You can do as he suggests and use (char *)(buffer)
, but I disagree with this stylistically.
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
.
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])
.
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
回答2:
You aren't passing the address to the buffer correctly.
(char *)(&buffer)
tells the compiler to take the address of buffer
instead of using the pointer contained in buffer
which of points to the memory allocated with new. To get the address of the buffer itself change it to the following.
(char *)(buffer)
来源:https://stackoverflow.com/questions/11159842/c-writing-int-buffer