为什么ifstream没有读到最后?

时间:2010-04-25 03:14:31

标签: c++ std fstream

我正在做一个类似记事本的程序。要从文件中获取文本,我通过执行

将每个字符读入缓冲区
while (!file.EOF())
{
  mystr += file.get();
}

然而,如果我加载一个exe,它会在MZ之后停止但是Notepad会读取整个exe。 我将ifstream设置为二进制模式,但仍然没有运气。我究竟做错了什么? 感谢

代码: (杂乱)

void LoadTextFromString(HWND ctrl, char* dirtypath, bool noquotes)
{
char *FileBuffer;

char *buf;

int count;
count = 0;

bool hasDot = false;
vector<int> quotes;
vector<string> files;
string temp;


if (noquotes)
{

    goto noqu;
}

while(dirtypath[count] != 0)
{
    if (dirtypath[count] == 34)
    {
        quotes.push_back(count);
    }
    count +=1;
}
if (quotes.size() < 3 || quotes.size() % 2 != 0)
{
    return;
}

for (int i = 0; i < quotes.size(); i += 2)
{

    temp = "";
    for (int j = quotes[i] + 1; j < quotes[i + 1]; ++ j)
    {
        temp += dirtypath[j];
    }

    files.push_back(temp);
}

for(int i = 0; i < files.size(); ++i)
{
noqu:
if (!noquotes)
{
FileBuffer = (char*)files[i].c_str();
}
else
{
FileBuffer = dirtypath;
}



ifstream *tf;
tf = new ifstream(FileBuffer,ios::binary);

ifstream *file;
file = new ifstream(FileBuffer,ios::binary);
if(file->fail())
{
    return;
}
int thelength;
thelength = 0;

while (!tf->eof())
{
    if (tf->get() == 10)
    {
        thelength +=1;
    }

    thelength +=1;
}
tf->close();

if(thelength == 0)
{
    SetWindowTextA(ctrl,"");
    return;
}
buf = new char[thelength + 1];

int lenn;
lenn = 0;
char cr ;
cr = 10;
char tmp;

while (!file->eof())
{

    buf[lenn] = file->get();
    if (buf[lenn] == cr) 
    {
        tmp = 13;
        buf[lenn] = tmp;

        buf[lenn + 1] = cr;
        lenn += 1;
    }
    lenn += 1;



}
buf[lenn - 1] = 0;

file->read(buf,lenn);
SetWindowTextA(ctrl,buf);
file->close();

}
delete(buf);

}

1 个答案:

答案 0 :(得分:3)

  

然而,如果我加载一个exe它停止   在MZ之后

.exe类型的文件可以包含所有类型的字节,甚至是0,你需要在附加到字符串之前检查字节值。

关于MZ