Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从C++;使用ifstream_C++_C_Binaryfiles - Fatal编程技术网

C++ 从C++;使用ifstream

C++ 从C++;使用ifstream,c++,c,binaryfiles,C++,C,Binaryfiles,我有以下用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("%X\n", buff); }else{ printf("File do

我有以下用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("%X\n", 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];
charfbuff[4];
ifstream文件(“image.jpg”,ios::binary);
if(file.is_open()){
文件读取(fBuff,sizeof(char)*4);
}否则{
cout溶液:

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

我想这就是你需要的

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;
}
std::ifstream文件;
未签名的短buff;
open(“image.jpg”,std::ios::in | std::ios::binary);
if(file.is_open()==true)
{
if(file.read(reinterpret_cast(&buff),sizeof(buff))!=0)

STD::这个问题似乎是偏离主题的,因为它是关于语言翻译服务的。@ MtTimeNeMs:我只想在C++中使用对应的 Frad()/Case>。LyGun然后就这样保留它。如果你不需要改变它,那么,不要,它在C++中是好的。代码是有效的(如果过时)在C++中,为什么要修复那些没有被破坏的东西?但是如果YPU希望看我能用C或C++写一个代码。我以前使用过这个函数,它给了我错误的数据。@ LyGun它对每个人都很好:也许复习这个教程www. cPLUS PLU.COD/DOC/TURBORAL/FILES/[你应该想要<代码>ary
在文件中。open就是这样。
中的差异重新解释了转换。谢谢。
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;
}