C++从二进制文件写入和读取双精度矩阵
在我的上一个问题之后出现了一个新问题:
我已经扩展了代码来执行矩阵二进制文件 I/O,并且在测试简单的写入和读取操作时,我仅检索了矩阵的第一行...
我没有设法找到我的错误,这是新代码:
double** bytes_to_matrix_block(std::ifstream& iF, int size1, int size2) {
double** m = new double*[size1];
double read;
int i = 0, j = 0;
if(!iF) {
std::cout << "opening file for reading error";
throw 1;
}
while(i < size1 && !iF.eof()) {
m[i] = new double[size2];
while(j < size2 && !iF.eof()) {
iF.read( reinterpret_cast<char*>( &read ), sizeof read );
m[i][j] = read;
std::cout << read << ", ";
j++;
}
std::cout << std::endl;
i++;
}
if(i < size1 || j < size2) {
std::cout << "premature end of file while reading..." << std::endl;
throw 1;
}
return m;
}
void matrix_block_to_bytes(double** m, int size1, int size2, std::ofstream& oF){
if(!oF){
std::cout << "opening file for writing error";
throw 1;
}
double cdbl;
for(int i = 0; i < size1; i++){
for(int j = 0; j < size2; j++){
cdbl = m[i][j];
std::cout << cdbl << ", ";
oF.write( reinterpret_cast<char*>( &cdbl ), sizeof cdbl );
}
std::cout << std::endl;
}
}
提前致谢
Here comes a new issue after my previous question :
I've extended the code to perform matrix binary files I/O and when testing a simple write and read operation, I retrieved only the first line of the matrix...
I don't have managed to find my error, here is the new code :
double** bytes_to_matrix_block(std::ifstream& iF, int size1, int size2) {
double** m = new double*[size1];
double read;
int i = 0, j = 0;
if(!iF) {
std::cout << "opening file for reading error";
throw 1;
}
while(i < size1 && !iF.eof()) {
m[i] = new double[size2];
while(j < size2 && !iF.eof()) {
iF.read( reinterpret_cast<char*>( &read ), sizeof read );
m[i][j] = read;
std::cout << read << ", ";
j++;
}
std::cout << std::endl;
i++;
}
if(i < size1 || j < size2) {
std::cout << "premature end of file while reading..." << std::endl;
throw 1;
}
return m;
}
void matrix_block_to_bytes(double** m, int size1, int size2, std::ofstream& oF){
if(!oF){
std::cout << "opening file for writing error";
throw 1;
}
double cdbl;
for(int i = 0; i < size1; i++){
for(int j = 0; j < size2; j++){
cdbl = m[i][j];
std::cout << cdbl << ", ";
oF.write( reinterpret_cast<char*>( &cdbl ), sizeof cdbl );
}
std::cout << std::endl;
}
}
Thanks by advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
阅读时,忘记将新行的 j 重置为 0
When reading, you forget to reset j to 0 for new lines