c++ - 解析文件头

标签 c++

我正在处理图像。我想从标题中提取它的宽度和高度。

宽度表示在位置

  size
   4B   width
   4B   height

它们以特定索引表示。

我尝试解析它并用代码提取它

    ifstream f(name, ios::binary | ios:: in ); // reading a file in binary
    ostringstream ob;

    if ( f.fail()){   // fail test
        return false;
    }

     f.seekg (0, f.end);
     int length = f.tellg();   // length of the file
     memory = new char[length]; // allocate array of chars
     f.read (memory, length);  // read the content of the file into an array
     f.seekg (0, f.beg);    // point back at the beginning of the file.

他们每个人都有 4B ,所以使用 for 循环

for ( int i = index ; i <4 ;i++){
     cout << hex<< memory[i];
}

或者我什至尝试过使用

将它转换成数字
   string a;
   for ( int i = index; i < 4 ;i++{
       a+=memory[i];
   }
   cout <<  atoi( a.c_str() )   << endl;

应该输出一个数字,但它输出了一些不可读的格式。

最佳答案

您正在阅读文件之后而不是之前寻找文件的开头。您需要切换 read()seekg():

f.seekg (0, f.beg);    // point back at the beginning of the file.
f.read (memory, length);  // read the content of the file into an array

关于c++ - 解析文件头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36099990/

相关文章:

C++ WIN32 : where to put code that executes as program is running

c++ - 显式特化不能是友元声明

c++ - operator>> 执行期间出错:C++ 没有运算符匹配这些操作数 操作数类型为:std::istream >> const double error

c++ - 使用 Qt/C++ 从单独的线程发出对象时如何避免复制?

c++ - 如何连接到蓝牙低功耗设备

c++ - dynamic_cast 不保证一个有效的、完整的对象?

c++ - Vulkan 中的设备到设备复制

c++ - 在构造函数调用期间将 this 传递给对象内的对象

c++ - 为什么有些包含文件只驻留在 tr1 中?

c++ - 带有 const 的外部 "C"