请教:我的VC++代码中关于文件读写的问题
为了读写一些数据,我定义了如下结构:
struct{
BYTE length1;
BYTE length2;
WORD length3;
WORD length4;
CString name;
}PROJECTA
现在我需要把这些相关数据写到一个文件(C:\P1.ndt)中去,有如下函数:
SaveProject(LPCTSTR lpszPathName)//lpszPathName为C:\P1.ndt
{
CFile file;
CFileException fe;
// 打开文件
if (!file.Open(lpszPathName, CFile::modeCreate |
CFile::modeReadWrite | CFile::shareExclusive, &fe))
{
// 失败
ReportSaveLoadException(lpszPathName, &fe,
TRUE, AFX_IDP_INVALID_FILENAME);
// 返回
return ;
}
//结构的对象
PROJECTA project_a;
CString Pathname = "d:\\get\\igma";
//保存数据
project_a.length1 = (BYTE) 24;
project_a.length2 = (BYTE) Pathname.GetLength());
project_a.length3 = (WORD) 880;
project_a.length4 = (WORD) 980;
project_a.name = Pathname;
//写文件
file.Write((LPSTR)&project_a, 6+Pathname.GetLength());
//关闭文件
file.Close();
return;
}
为了读出文件(C:\P1.ndt)中的数据又定义了如下读文件函数:
ReadProject(LPCTSTR lpszPathName)//lpszPathName为C:\P1.ndt
{
//结构的对象
PROJECTA project_a;
CFile file;
CFileException fe;
DWORD dwFileSize;//文件大小
// 打开文件
if (!file.Open(lpszPathName, CFile::modeRead | CFile::modeReadWrite, &fe))
{
// 失败
ReportSaveLoadException(lpszPathName, &fe,
TRUE, AFX_IDP_INVALID_FILENAME);
// 返回
return ;
}
//读文件
if ( file.Read((LPSTR)&project_a, dwFileSize) != dwFileSize )
{
// 大小不对,返回。
return ;
}
//读取数据
int L1 = project_a.length1;
int L2 = project_a.length2;
int L3 = project_a.length3;
int L4 = project_a.length4;
CString Pathname = project_a.name;
//关闭文件
file.Close();
return;
}
但是这样读文件的话执行到int L3 = project_a.length3就会出错。如果改成如下代码:
ReadProject(LPCTSTR lpszPathName)//lpszPathName为C:\P1.ndt
{
//结构的对象
PROJECTA project_a;
CFile file;
CFileException fe;
DWORD dwFileSize;//文件大小
// 打开文件
if (!file.Open(lpszPathName, CFile::modeRead | CFile::modeReadWrite, &fe))
{
// 失败
ReportSaveLoadException(lpszPathName, &fe,
TRUE, AFX_IDP_INVALID_FILENAME);
// 返回
return ;
}
//读文件
if ( file.Read((LPSTR)&project_a, 6) != 6 )
{
// 大小不对,返回。
return ;
}
//读取数据
int L1 = project_a.length1;
int L2 = project_a.length2;
int L3 = project_a.length3;
int L4 = project_a.length4;
if ( file.Read((LPSTR)project_a.name.GetBuffer(L2), dwFileSize-6) != dwFileSize-6)
{
// 大小不对,返回NULL。
return NULL;
}
CString Pathname = project_a.name;
//关闭文件
file.Close();
return;
}
此时返回的Pathname并不是我们保存的值"d:\\get\\igma",而是乱码一堆。
请教高手们,到底是哪里出了问题呢?帮我把把脉~~~
有点长,烦请务必帮忙。多谢!