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

sup*_*ame 2 c++ fstream vector

一周前我还在研究那个位图I/O问题.我再次陷入困境,所以我决定从一种熟悉的I/OI开始,并使其更像我需要的稳定(一次检查每个字节(像素)并输出到基于该文件的文件字节的值).

我开始使用一个程序来读取和检查文本文件的每个字符,如果它高于某个阈值则输出"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);
}
Run Code Online (Sandbox Code Playgroud)

输出(来自message.txt):

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

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

Rem*_*anu 8

以二进制模式打开您的流:

sourcefile.open("Input.FILE", ios::binary);
Run Code Online (Sandbox Code Playgroud)


Jon*_*age 6

如果你查看ascii代码25是什么意思,end of medium那么很有可能如果你在ascii模式下阅读,任何后续的读取都不会起作用.

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

sourcefile.open("Input.FILE", ios::binary);
Run Code Online (Sandbox Code Playgroud)

  • @jaffe:它与ASCII无关.您在Windows中遇到C/C++"文本模式",其中^ Z(Ctrl Z,ASCII 26)标记文本文件中的数据结尾.我记得那可能源于CP/M中的类似行为,可能具有不同的控制特征.您可以通过命令如"type con"在命令解释程序中测试该行为,并首先在行上使用Ctrl Z终止输入,然后是换行符.在任何控制台窗口中,您还可以在F6功能键上使用Ctrl Z. (3认同)

Oli*_*rth 5

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