为什么这个数据流在字节26结束

Why does this Stream of data end at byte 26?

本文关键字:字节 结束 数据流 为什么      更新时间:2023-10-16

我仍在处理一周前的位图I/O问题。我又陷入了困境,所以我决定从一种我熟悉的I/O类型开始,并使其更像我所需要的(即一次检查每个字节(像素),并根据该字节的值输出到文件)。

我从一个程序开始,该程序读取并检查文本文件的每个字符,如果超过某个阈值,则输出"Z",如果低于某个阈值则输出"a"。

这个程序运行得很好,所以我决定把它从文件中的字符改为字节。

现在,我遇到了问题。文件的前26个(字节0-25)字节是正确的,但其余的是0或-1,这取决于我使用的是ifstream.get()还是ifstream.read

输入文件Input.FILE是在十六进制编辑器中创建的,仅包含0x00-0xFF。它的长度是256字节。

代码:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
   ifstream sourcefile;
   ofstream output;
   ofstream output2;
   output.open("output.txt");
   output2.open("messages.txt");
   sourcefile.open("Input.FILE");
   vector<char> data(256);
   sourcefile.read(&data[0],256);
   sourcefile.seekg(0,ios::beg);
   for(int i = (int) 0x00 ; i < data.size() ; i++)
   {
      output2 << "Value data[" << i << "] = " << (int) data[i] << endl;
      if((int)data[i] < 0)
      {
         // since I can't make an unsigned char vector, I use this to convert
         // it to the correct number. Could this be the problem?
         data[i] = 256 + data[i];
         output2 << "less than zero." << endl;
      }
      if(data[i] > 64)
      {
         data[i] = 0xFF;
         output2 << "greater than 64, set to 0xFF." << endl;
      }
      else if(data[i] < 64)
      {
         data[i] = 0x00;
         output2 << "less than 64, set to 0x00." << endl;
      }
      else
      {
         // This is most likely pointless, but I didn't want to take a chance
         data[i] = 0x75;
         output2 << "neither greater nor less than 64? Set to 0x75." << endl;
      }
      output2 << endl;
   }
   output.write(&data[0],256);
}

输出(来自message.txt):

注:data[0-25]包含正确的值


值data[19]=19小于64,设置为0x00。
值data[20]=20小于64,设置为0x00。
值data[21]=21小于64,设置为0x00。
值data[22]=22小于64,设置为0x00。
值data[23]=23小于64,设置为0x00。
值data[24]=24小于64,设置为0x00。
值data[25]=25小于64,设置为0x00。
值data[26]=0小于64,设置为0x00。

以二进制模式打开流:

sourcefile.open("Input.FILE", ios::binary);

如果你查找什么是ascii代码25,你会发现它的意思是end of medium,所以如果你在ascii模式下阅读,任何后续的阅读都很有可能不起作用。

尝试指定您使用的是二进制文件:

sourcefile.open("Input.FILE", ios::binary);

尝试sourcefile.open("Input.FILE", std::ifstream::binary)

也许您1)使用了一个过时的操作系统(如CP/M或DOS),其中内联控件Z表示EOF,2)没有以二进制模式打开文件。

尝试sourcefile.open("Input.FILE", ios::binary);