简体   繁体   中英

Reading binary file into char array in c++

std::streampos size;
char * memblock;

std::ifstream input ("A.JPG", std::ios::in|std::ios::binary|std::ios::ate);

if (input.is_open())
{
    size = input.tellg();
    memblock = new char [size];
    input.seekg (0, std::ios::beg);
    input.read (memblock, size);
    input.close();

    std::cout << "[INPUT]the entire file content is in memory " << sizeof(memblock) << " \n";

}
delete[] memblock;

I would like to use the ifstream to read A.JPG (28KB) and save it into the array memblock. But why do the size of the memblock is 4 instead of 28403 while the variable size is equal to 28403?

Thank you.

因为memblock是一个指针,所以sizeof运算符的计算结果是指针变量的大小,即 4 个字节。

Thanks all and finally I used the vector instead. Because seems it is hard to display the result I want (length of the actual char array)

std::vector <char> memblock(0);
  if (input.is_open())
  {
    size = input.tellg();
    //memblock = new char [size];
    memblock.resize(size);
    input.seekg (0, std::ios::beg);
    input.read (&memblock[0], size);
    input.close();


    //std::cout << "[INPUT]the entire file content is in memory " << ((char *)(&memblock+1) - (char *)memblock) / (sizeof(memblock[0])) << " \n";
    std::cout << "[INPUT]the entire file content is in memory " << memblock.size() << " \n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM