从二进制文件c ++中读取16位整数

use*_*834 1 c++ binary sizeof

我不确定我是否正确这样做,所以我想查看我的代码.它有效,但我不确定它的工作正常.我需要它来读取二进制文件,并将16位整数存储在所需的确切大小的整数数组中.我试图这样做sizeof(storage[i]),我可以看到我是否存储16位,但它说32(我猜是因为int自动分配4个字节?

        void q1run(question q){
        int end;
        std::string input = q.programInput;
        std::ifstream inputFile (input.c_str(), ios::in | ios::binary);                     //Open File
        if(inputFile.good()){                                       //Make sure file is open before trying to work with it
                                                                    //Begin Working with information
           cout << "In File:  \t" << input << endl;
           inputFile.seekg(0,ios::end);
           end=inputFile.tellg();
           int numberOfInts=end/2;
           int storage[numberOfInts];
           inputFile.clear();
           inputFile.seekg(0);
           int test = 0;


           while(inputFile.tellg()!=end){       
               inputFile.read((char*)&storage[test], sizeof(2));
               cout << "Currently at position" << inputFile.tellg() << endl;
               test++;
           }

           for(int i=0;i<numberOfInts;i++){
               cout << storage[i] << endl;
           }
       }else{
           cout << "Could not open file!!!" << endl;
      }
 }
Run Code Online (Sandbox Code Playgroud)

编辑:::::::::::::::::::::::::::::::::::::::::::::;

我将read语句更改为:

      inputFile.read((char*)&storage[test], sizeof(2));
Run Code Online (Sandbox Code Playgroud)

和要键入的数组short.现在它很好用,除了输出有点奇怪:

      In File:        data02b.bin
      8
      Currently at position4
      Currently at position8
      10000
      10002
      10003
      0
Run Code Online (Sandbox Code Playgroud)

我不确定.bin文件中有什么,但我猜0应该不存在.大声笑

Sca*_*nth 7

使用:int16_tin <cstdint>.(保证16位)

Shorts和ints可以具有各种尺寸,具体取决于架构.

  • Nitpick - 保证16位,但不是两个字节. (2认同)

Dar*_*rer 5

是的, int 是 4 个字节(在 32 位 x86 平台上)。

你有两个问题:

  1. 正如亚历克蒂尔在评论中正确提到的那样,您将存储声明为 int,这意味着 4 个字节。没问题,真的 - 您的数据将适合。
  2. 实际问题:您正在读取文件的行:inputFile.read((char*)&storage[test], sizeof(2));实际上正在读取 4 个字节,因为 2 是整数,因此sizeof(2)是 4。您不需要sizeof那里。