我正在从该类重新创建一些System.IO函数。 当我设置一个缓冲区并分配n个字节时,它将读取字节,然后将随机字节添加到该缓冲区的末尾。
例如:
我的主要:
int main(int argc, char *args[])
{
SetConsoleTitle(TEXT("Stream Test."));
cout<<"Press any Key to begin reading.";
cin.get();
const char* data = File::ReadAllBytes(args[1]);
Stream* stream = new Stream(data);
char* magic = new char[8];
stream->Read(magic, 0, 8);
magic[8] = '\0';
cout<<magic<<endl<<endl;
delete[]data;
cout<<"Press any key to quit.";
cin.get();
return 0;
}
这是我的System :: IO名称空间+流类:
namespace System
{
namespace IO
{
class File
{
public:
static char* ReadAllBytes(const char *name)
{
ifstream fl(name, ifstream::in|ifstream::binary);
fl.seekg( 0, ifstream::end );
size_t len = fl.tellg();
char* ret = new char[len+1];
ret[len] = '\0';
fl.seekg(0);
fl.read(ret, len);
fl.close();
return ret;
}
//not sure of this use yet.
static size_t fileSize(const char* filename)
{
ifstream in(filename, ifstream::in | ifstream::binary);
in.seekg(0, ifstream::end);
return in.tellg();
}
};
class Stream
{
public:
const char *_buffer;
__int64 _origin;
__int64 _position;
__int64 _length;
__int64 _capacity;
bool _expandable;
bool _writable;
bool _exposable;
bool _isOpen;
static const int MemStreamMaxLength = 2147483647;
Stream()
{
InitializeInstanceFields();
}
Stream(const char *buffer)
{
_buffer = buffer;
_length = strlen(_buffer);
_capacity = _length;
_position = 0;
_origin = 0;
_expandable = false;
_writable = true;
_exposable = true;
_isOpen = true;
}
int ReadByte()
{
if (_position >= _length)
return -1;
return _buffer[_position++];
}
void Read(char* &buffer, int offset, int length)
{
if((_position + offset + length) <= _length)
{
memcpy( buffer, _buffer + (_position + offset), length );
_position += length;
}
}
private:
void InitializeInstanceFields()
{
_origin = 0;
_position = 0;
_length = 0;
_capacity = 0;
_expandable = false;
_writable = false;
_exposable = false;
_isOpen = false;
}
};
}
}
这就是最终发生的事情:
任何人都可以解释为什么会发生这种情况,我该如何修复或其他什么?我是C ++的新手,所以任何解释都会有所帮助。另外请不要批评我的脚本,我知道它可能不好,过时,弃用等等,但我愿意学习,任何帮助建议都会变得更好。 :)
答案 0 :(得分:0)
您只能在C风格的字符串上使用operator << (char *)
,而不能使用任意字符数组。您希望如何知道要输出多少个字符?
答案 1 :(得分:0)
我猜测文件没有正确打开,因此魔法缓冲区根本没有设置,而是留下了初始化的垃圾数据:
如果构造函数未成功打开文件,则该对象 仍然创建,但没有文件与流缓冲区关联 并且设置了流的failbit(可以使用inherited进行检查) 成员失败)。 http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
尝试在此过程中添加更多错误检查(使用cout),尤其是在打开和读取缓冲区时。也许将魔术缓冲区设置为零或成功时会被覆盖的可识别的东西。