从 matlab 中的二进制文件读取不正确
Incorrect reading floats from binary file in matlab
我正在尝试在 matlab 中读取存储在二进制文件中的浮点数数组。最初文件是通过内存映射技巧在 c++ 代码中创建的。
C++代码:
#include <iostream>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
const char* filePath = "test_file.dat";
const size_t NUM_ELEMS = 11;
/* Write the float array to the binary file via memory mapping */
const size_t NUM_BYTES = NUM_ELEMS * sizeof(float);//array of the 11 floats;
int fd = open(filePath, O_RDWR | O_CREAT | O_TRUNC, 0);//open file
lseek (fd, NUM_BYTES - 1, SEEK_SET);//stretch the file size
write(fd, "", 1);//write empty string at the end of file
float* mappedArray = (float*)mmap(0, NUM_BYTES, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);//map array to the file
for(size_t i = 0; i < NUM_ELEMS; ++i)//fill array
mappedArray[i] = static_cast<float>(i) / 10.0f;
munmap(mappedArray, NUM_BYTES);
close(fd);
/* Test reading the recorded file*/
std::ifstream fl(filePath, std::ios::in | std::ios::binary);
float data = 0.0f;
for(size_t i = 0; i < NUM_ELEMS; ++i)
{
fl.read(reinterpret_cast<char*>(&data), sizeof(data));
std::cout<<data<<"n";
}
fl.close();
}
从C++代码中读取文件显示正确的结果 - 文件已成功记录。从C++读取的结果:
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0,8
但是,尝试从 matlab 读取此文件会产生错误(数据不正确(:
矩阵代码:
function out = readDataFromFile()
fid = fopen('test_file.dat','r','b');
out = fread(fid, 11, '*float');
fclose(fid);
end
从 matlab 读取的结果:
0 -429492128 -428443584 -6,3526893E-23 -429492160 8,8281803e-44 -6,3320104E-23 4,1723293E-08 -428443616 2,7200760e+23 4,6006030e-41
我想指出的是,如果我编写uint8_t(或无符号字符(数组,则从 matlab 读取此文件会成功。我在 matlab 中做错了什么?
我的系统 - 64 位 Ubuntu 13.04, c++ 编译器 - gcc 4.8, matlab - 2013a
通过替换解决了这个问题
fid = fopen('test_file.dat','r','b');
在
fid = fopen('test_file.dat','r');
相关文章:
- C++ 读取文件读取文件不正确
- C++:读取字符是不正确的
- 读取来自提升binary_iarchive不正确的数据
- 使用 c++ 时从二进制文件中读取 int 不正确
- 为什么当我使用双精度时,Qt<->Matlab 正确写入和读取我的字节,但存储 uint32 的字节不正确?
- 尝试使用 ifstream 读取数据后显示不正确的数字
- 结构C++ – 从文件中读取不正确
- 结束标记 xml 验证在提升 ptree 读取 xml 中不正确
- 为什么我的getline不正确读取.csv文件
- 逐行从文件读取到矢量对于<T>二进制数据C++不正确
- 从堆栈中读取字符后,如何修复不正确的文件输出
- 如果语句内部循环不读取完全正确的代表显示错误
- 读取PPM文件并使用Opengl和c++进行显示.颜色不正确
- 写入和读取 bin 文件数据不正确
- boost::local_time 读取不正确的iso_extended_format
- 从 matlab 中的二进制文件读取不正确
- 读取并显示文件,但输出不正确
- 不正确的输入和读取
- UDP数据读取不正确(延迟)
- 文件读取不正确