【发布时间】:2011-06-06 22:38:18
【问题描述】:
我仍在处理一周前的位图 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);
}
输出(来自message.txt):
注意:data[0-25] 包含正确的值
...
数值数据[19] = 19 小于 64,设置为 0x00。
数值数据[20] = 20 小于 64,设置为 0x00。
值 data[21] = 21 小于 64,设置为 0x00。
数值数据[22] = 22 小于 64,设置为 0x00。
数值数据[23] = 23 小于 64,设置为 0x00。
数值数据[24] = 24 小于 64,设置为 0x00。
数值数据[25] = 25 小于 64,设置为 0x00。
value data[26] = 0 小于 64,设置为 0x00。
【问题讨论】:
-
您可以使用 Iostream 库的错误标志来找到出现问题的确切点。
-
这是一个很好的建议,但错误标志对我没有多大帮助。