使用 c++ 将二进制文件 (jpg) 读取到字符串
Read a binary file (jpg) to a string using c++
我需要将jpg文件读取为字符串。我想将此文件上传到我们的服务器,我只是发现 API 需要一个字符串作为此图片的数据。我遵循了我之前提出的一个问题中的建议 使用 c++ 将图片上传到服务器。
int main() {
ifstream fin("cloud.jpg");
ofstream fout("test.jpg");//for testing purpose, to see if the string is a right copy
ostringstream ostrm;
unsigned char tmp;
int count = 0;
while ( fin >> tmp ) {
++count;//for testing purpose
ostrm << tmp;
}
string data( ostrm.str() );
cout << count << endl;//ouput 60! Definitely not the right size
fout << string;//only 60 bytes
return 0;
}
为什么它停在 60 岁?60岁是个奇怪的角色,我该怎么办才能将jpg读成字符串?
更新
几乎在那里,但是在使用建议的方法后,当我将字符串重写到输出文件时,它失真了。发现我还应该通过ofstream::binary
指定ofstream处于二进制模式。做!
顺便问一下ifstream::binary
和ios::binary
有什么区别,ofstream::binary
有缩写吗?
以二进制模式打开文件,否则它将具有有趣的行为,并且它将以不适当的方式处理某些非文本字符,至少在Windows上是这样。
ifstream fin("cloud.jpg", ios::binary);
此外,您可以一次读取整个文件,而不是 while 循环:
ostrm << fin.rdbuf();
不应将文件读入字符串,因为 jpg 包含 0 的值是合法的。但是,在字符串中,值 0 具有特殊含义(它是字符串指示符的末尾,又名 \0(。相反,您应该将文件读入向量。您可以像这样轻松执行此操作:
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
int main(int argc, char* argv[])
{
std::ifstream ifs("C:\Users\Borgleader\Documents\Rapptz.h");
if(!ifs)
{
return -1;
}
std::vector<char> data = std::vector<char>(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
//If you really need it in a string you can initialize it the same way as the vector
std::string data2 = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
std::for_each(data.begin(), data.end(), [](char c) { std::cout << c; });
std::cin.get();
return 0;
}
尝试以二进制模式打开文件:
ifstream fin("cloud.jpg", std::ios::binary);
猜测,您可能正在尝试在Windows上读取文件,并且第61个字符可能0x26 - 一个control-Z,(在Windows上(将被视为标记文件的末尾。
至于如何最好地进行阅读,您最终会在简单和快速之间做出选择,如之前的答案所示。
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 读取字符串文本输入以创建 2D 矢量
- 罗马数字到阿拉伯语 (vinculum) - 读取字符串中的字符
- C++:从文件中读取字符串和整数,并获得最大数字
- C++,从文件中读取字符串,分段错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 如何从内存中读取字符串?
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 我需要C++读取字符串数组中每个单词的第一个字母
- 读取字符串C++的字符时出错
- 读取字符串直到标志 (C++)
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++输入文件流无法从文件中读取字符串
- 读取字符串字符时出错
- 如何读取<字符串,矢量<对<int,字符串的映射>>>
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- C++ 使用 Strtok 读取字符串字符时出错
- 使用 getline 读取字符串,但每行中都有换行符