int TForm1::ReadFileToMemoByFileName(TMemo* pMemo,AnsiString strFileName){
if(strFileName==""){
return -1;//文件名不存在
}
AnsiString ExePath = ExtractFilePath(ParamStr(0));//可执行文件的路径
ExePath += strFileName;
if(!FileExists(ExePath)){ //文件是否存在
return 1; //文件不存在
}
int iFileHandle;
int iFileLength;
char* pszBuffer;
pMemo->Clear();
try
{
iFileHandle = FileOpen(ExePath, fmOpenRead); //以读方式打开文件
iFileLength = FileSeek(iFileHandle, 0, 2); //确定文件长度
FileSeek(iFileHandle, 0, 0); //文件指针指到开始
pszBuffer = new char[iFileLength + 1];
if(pszBuffer==NULL){
return 2; //内存申请失败
}
FileRead(iFileHandle, pszBuffer, iFileLength); //从文件中读取指定长度的内容到pszBuffer
FileClose(iFileHandle); //关闭文件
String str(pszBuffer);
pMemo->Lines->Clear();
pMemo->Lines->Text = str;
delete[] pszBuffer;
}
catch (...)
{
ExePath += " 文件读取失败!!!";
Application->MessageBox(ExePath.c_str(),"File Error", IDOK);
}
return 0;
}
if(strFileName==""){
return -1;//文件名不存在
}
AnsiString ExePath = ExtractFilePath(ParamStr(0));//可执行文件的路径
ExePath += strFileName;
if(!FileExists(ExePath)){ //文件是否存在
return 1; //文件不存在
}
int iFileHandle;
int iFileLength;
char* pszBuffer;
pMemo->Clear();
try
{
iFileHandle = FileOpen(ExePath, fmOpenRead); //以读方式打开文件
iFileLength = FileSeek(iFileHandle, 0, 2); //确定文件长度
FileSeek(iFileHandle, 0, 0); //文件指针指到开始
pszBuffer = new char[iFileLength + 1];
if(pszBuffer==NULL){
return 2; //内存申请失败
}
FileRead(iFileHandle, pszBuffer, iFileLength); //从文件中读取指定长度的内容到pszBuffer
FileClose(iFileHandle); //关闭文件
String str(pszBuffer);
pMemo->Lines->Clear();
pMemo->Lines->Text = str;
delete[] pszBuffer;
}
catch (...)
{
ExePath += " 文件读取失败!!!";
Application->MessageBox(ExePath.c_str(),"File Error", IDOK);
}
return 0;
}