使用 ifstream 从C++文件中读取二进制无符号短整型
Reading binary unsigned short from a file in C++ using ifstream
我有以下由C语言编写的示例代码。
以下代码的函数从 jpg 图像文件中读取前两个字节。
unsigned short buff;
FILE *file;
file = fopen("image.jpg", "rb");
if(file != NULL){
fread(&buff, sizeof(unsigned short), 1, file);
fclose(file);
printf("%Xn", buff);
}else{
printf("File does not exists.");
}
结果:
D8FF
这就是我试图在C++中写的:
char fBuff[4];
ifstream file("image.jpg", ios::binary);
if(file.is_open()){
file.read(fBuff, sizeof(char)*4);
}else{
cout << "File does not exists." << endl ;
}
for(int i=0;i<4;i++)
cout << ios_base::hex << fBuff[i];
c ++代码中的问题,它错误地给了我数据。
我想要的是,将fread()
更改为C++中相应的相应功能。但是其他函数如fopen
、fclose
、printf
等,我知道C++对应的。
我认为这就是你需要的。
std::ifstream file;
unsigned short buff;
file.open("image.jpg", std::ios::in | std::ios::binary);
if (file.is_open() == true)
{
if (file.read(reinterpret_cast<char *>(&buff), sizeof(buff)) != 0)
std::cout << std::hex << std::uppercase << buff << std::endl;
file.close();
} else {
std::cout << "File does not exists" << std::endl;
}
解决方案:
istream& read (char* s, streamsize n)
s - Pointer to an array where the extracted characters are stored.
n - Number of characters to extract.
reinterpret_cast<char *> might be needed for some people
这会像阅读一样读取文件。
istream& get (streambuf& sb, char delim);
istream& getline (char* s, streamsize n );
相关文章:
- 正在读取二进制文件(is_open)
- 如何从dicom文件中读取二进制数据
- C++用于从流中读取二进制值的任何标准库
- readsome() 适合在 Windows 上读取二进制数据吗?
- 读取二进制文件并解释为整数
- 读取二进制文件直到结束 c++
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- 读取二进制文件的惯用C++17标准方法是什么
- 从末尾读取二进制文件
- C++逐个字符读取二进制文件字符
- 读取二进制文件大小的短自上周以来停止工作
- 读取二进制文件时出现问题
- 读取二进制文件时如何输出?
- C++:如何在线程中读取二进制文件并将其写入另一个线程?
- 在C 中读取二进制文件会返回意外值
- 尝试读取二进制文件会清除文件本身
- C 读取二进制文件
- 通过C 读取二进制文件的问题
- 用ifstream read()读取二进制的结构
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用