MFC:将整个文件读取到缓冲区
我处理了一些代码,但无法正确读取整个文件…输出中附加了很多垃圾。我该如何解决这个问题MFC:将整个文件读取到缓冲区,mfc,file-io,Mfc,File Io,我处理了一些代码,但无法正确读取整个文件…输出中附加了很多垃圾。我该如何解决这个问题 // wmfParser.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "wmfParser.h" #include <cstring> #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and on
// wmfParser.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "wmfParser.h"
#include <cstring>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CFile file;
CFileException exp;
if( !file.Open( _T("c:\\sample.txt"), CFile::modeRead, &exp ) ){
exp.ReportError();
cout<<'\n';
cout<<"Aborting...";
system("pause");
return 0;
}
ULONGLONG dwLength = file.GetLength();
cout<<"Length of file to read = " << dwLength << '\n';
/*
BYTE* buffer;
buffer=(BYTE*)calloc(dwLength, sizeof(BYTE));
file.Read(buffer, 25);
char* str = (char*)buffer;
cout<<"length of string : " << strlen(str) << '\n';
cout<<"string from file: " << str << '\n';
*/
char str[100];
file.Read(str, sizeof(str));
cout << "Data : " << str <<'\n';
file.Close();
cout<<"File was closed\n";
//AfxMessageBox(_T("This is a test message box"));
system("pause");
}
return nRetCode;
}
//wmfParser.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括“wmfParser.h”
#包括
#ifdef_调试
#定义新调试\u新
#恩迪夫
//唯一的应用程序对象
CWinApp-theApp;
使用名称空间std;
int_tmain(int-argc,TCHAR*argv[],TCHAR*envp[]
{
int nRetCode=0;
//初始化MFC并打印,失败时出错
如果(!AfxWinInit(::GetModuleHandle(NULL),NULL,::GetCommandLine(),0))
{
//TODO:更改错误代码以满足您的需要
_tprintf(_T(“致命错误:MFC初始化失败”);
nRetCode=1;
}
其他的
{
//TODO:在此处编写应用程序的行为代码。
文件文件;
cfileexp;
如果(!file.Open(_T(“c:\\sample.txt”),CFile::modeRead,&exp)){
exp.ReportError();
cout您的字符串不是以NULL结尾的。您需要使用memset(str,0,sizeof(str))初始化字符串str
;
我认为这可能更接近您要查找的内容:
/* first method */
ULONGLONG dwLength = file.GetLength();
cout << "Length of file to read = " << dwLength << '\n';
// make room for whole file, plus null
BYTE *buffer = (BYTE *) malloc(dwLength + 1);
file.Read(buffer, dwLength); // read whole file
*(buffer + dwLength) = '\0'; // add null
cout << "length of string : " << strlen(buffer) << '\n';
cout << "string from file: " << buffer << '\n';
free(buffer);
file.SeekToBegin(); // Back to the beginning
/* second method */
char str[dwLength + 1];
file.Read(str, dwLength + 1);
str[dwLength] = '\0';
cout << "Data : " << str <<'\n';
file.Close();
cout << "File was closed\n";
/*第一种方法*/
ULONGLONG dwLength=file.GetLength();
库特