将文件读入缓冲区 [英] reading file into buffer
本文介绍了将文件读入缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将文件的内容读取到缓冲区中,以准备在MFC应用程序中填充窗口.
我的代码是:
I am reading the contents of a file into a bufer ready to populate a window in an MFC app.
My code is:
//read file
CFile* pFile = new CFile(filePathAndName, CFile::modeRead);
ULONGLONG dwLength = pFile->GetLength();//I64u
char* buffer = new char[(int)dwLength];
UINT nActual = pFile->Read(buffer, dwLength);//sizeof(szBuffer));
但是,我总是在缓冲区的末尾得到大约10-12个字符的垃圾-通常看起来是这样的:
ýýýý««««««««îþ
谁能告诉我这是哪里来的,以及如何将其删除.如果文件为空,我什至可以得到它.
However, I lways get about 10-12 characters of garbage right at the end of the buffer - it usually looks something like:
ýýýý««««««««îþîþ
Can anyone tell me where this comes from and how to remove it please. I even get it if the file is empty.
推荐答案
Dave的答案是绝对正确的,但是更好的解决方法是
Dave''s answer is absolutely correct, however a better solution to the problem would be
//read file
CFile* pFile = new CFile(filePathAndName, CFile::modeRead);
ULONGLONG dwLength = pFile->GetLength();//I64u
char* buffer = new char[(int)dwLength + 1]; //Notice the +1
buffer[dwLength] = 0; //This will make the last character a null terminator
UINT nActual = pFile->Read(buffer, dwLength);//sizeof(szBuffer));
这将使您可以将文件内容与任何C ++函数一起用作普通字符串
This will allow you to use the file contents with any C++ function as a normal string
像这样读取时没有空终止符-因此您要添加缓冲区的末尾-什么设置字符串时的一行?您需要确保仅使用nActual字符-否则最后将得到垃圾:)
There is no null terminating character when reading like this - so you are adding the end of the buffer - what''s the line when you set your string? You need to make sure you use nActual characters only - otherwise you''ll get garbage at the end :)
这篇关于将文件读入缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文