C++ 将整个std::ifstream读取到堆
我不明白为什么这不起作用。据我所知,它似乎没有读取整个图像文件。。。虽然我不知道。我基本上有一些原始图像,我想读到堆上C++ 将整个std::ifstream读取到堆,c++,C++,我不明白为什么这不起作用。据我所知,它似乎没有读取整个图像文件。。。虽然我不知道。我基本上有一些原始图像,我想读到堆上 unsigned char* ReadImageFromFile(const char* FILENAME, unsigned int SIZE_BYTES) { unsigned char *data = (unsigned char*) malloc(SIZE_BYTES); std::ifstream image(FILENAME); image
unsigned char* ReadImageFromFile(const char* FILENAME, unsigned int SIZE_BYTES)
{
unsigned char *data = (unsigned char*) malloc(SIZE_BYTES);
std::ifstream image(FILENAME);
image.read((char*) data, SIZE_BYTES);
image.close();
return data;
}
尝试
std::ifstream映像(文件名,std::ios\u base::binary)
(注意ifstream的第二个参数。1)以二进制模式打开文件
2) 不要返回需要释放的原始指针
std::string readImageFromFile(const char* filename)
{
std::ifstream image(filename, std::ios::binary);
std::ostringstream data;
data << image.rdbuf();
return data.str();
}
std::string readImageFromFile(const char*filename)
{
std::ifstream映像(文件名,std::ios::binary);
std::ostringstream数据;
数据停止与C++混合,它将工作。首先,如果你使用C++,请不要使用MALROCK()如果你正在读取原始数据,你可能想用二进制模式打开文件。@ Alx1985,不,我们有更好的原语比<代码>新< /代码>。我们有容器,我们有智能指针-<代码>新< /代码>几乎从来都不是答案。请考虑。不使用Maloc或C样式的Casts。它们是一个麻烦的配方。也可以考虑读到一个STD::vector。更可能的是,问题是你不是在二进制模式下打开文件。如果你在Windows下(和大多数其他非UNIX系统),在文本模式下读取二进制文件将导致丢失数据:所有0x0D将被删除,第一个0x1A将终止输入。我需要返回原始ptr。我不想要std::string。我可能应该提到此代码正在微处理器上运行。好的,如果您喜欢,请更新答案以避免std::string
当然,它在嵌入式人群中很受欢迎!老实说,我确实需要这样做,因为我使用的是opencv,我需要用我从这个文件返回的指针敲打cv::Mat的数据指针。你可以将std::string很好地用于opencv或类似的工具。仅使用指针,你就会弄错。举个例子,你如何告诉ho返回w big?它是二进制的,结尾没有\0字符。请使用std::string或std::vector。然后使用std::string().c_str()或&std::vector[0]将指针传递给c-only函数。它将在函数结尾释放自身。
char* readImageFromFile(const char* filename)
{
std::ifstream image(filename, std::ios::binary);
std::ostrstream data;
data << image.rdbuf();
data.freeze();
return data.str();
}