为什么这个数据流在字节26结束
Why does this Stream of data end at byte 26?
我仍在处理一周前的位图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);
。
- 从不同线程使用int64的不同字节安全吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 在UNIX系统中使用DIR查找文件的字节大小
- 为什么在这个代码结束循环中没有得到结束
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- std::当在256字节边界上写入整数时,流的奇怪行为
- 试图对缓存进行跨步测试,但程序并没有结束
- 当比特(而不是字节)的顺序至关重要时的持久性
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何在文件中查找字节序列
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 为什么擦除方法会影响结束方法
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 字节到位运算符重载C++
- 在java中读取c++字节的位字段
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 删除映射和分割错误中的一个过去结束元素
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 为什么这个数据流在字节26结束