`
yidongkaifa
  • 浏览: 4059154 次
文章分类
社区版块
存档分类
最新评论

VC 文件操作CFile,fstream

 
阅读更多
		CFile tmpFile;
		ULONGLONG fileLen;
		
		tmpFile.Open(pTempCDRomPathW,CFile::modeRead);
	

		fileLen=tmpFile.GetLength();	//获取file文件中内容的长度;
		tmpFile.SeekToBegin(); //到达文件开头   

		BYTE *data =NULL;
		data  =new BYTE[fileLen+1];//定义一个存放数据的指针;
		memset(data  ,0,fileLen+1);//	将已开辟内存空间 data的,长度为len+1首 个字节的值设为值 0
		tmpFile.Read(data,fileLen);//读取文件内容并赋值给data;


		CFile fileEx(_T("f://023367xx.txt"),CFile::modeCreate|CFile::modeWrite);

		fileEx.SeekToBegin(); //到达文件开头   

		fileEx.Write(data,fileLen); //写入实际数据   

		fileEx.Close(); //关闭文件   

		delete [] data;


下面判断文件是否存在:

BOOL IsFileExist(LPCTSTR lpFileName)
{
	if(lpFileName==NULL)
		return FALSE;
	BOOL bExist = TRUE;
	HANDLE hFind;
	WIN32_FIND_DATA dataFind;
	hFind=FindFirstFile(lpFileName,&dataFind);
	if(hFind == INVALID_HANDLE_VALUE)
		bExist=FALSE;
	FindClose(hFind);
	return bExist;
}


另外一种操作文件的方法,逐行处理数据:

#include <fstream>
using namespace std;

char pName[100];
char pVersion[5];
int lineLength = 200; 
char *buffer = new char[lineLength];
BOOL TestFunc(void)
{
	wchar_t pTempCDRomPathW[100];
	char	pTempCDRomPath[100];

	sprintf(pTempCDRomPath,"%s\\SYSTEM.CNF",pCDRomPath);
	c2w(pTempCDRomPathW,100,pTempCDRomPath);

	if( TRUE == IsFileExist(pTempCDRomPathW))
	{
#define VERSION_LEN 4
		fstream fs( pTempCDRomPath, ios::in );
		if( fs!= NULL )
		{
			char *p=NULL;
			char *q=NULL;
			int j=0;
			while(fs.getline(buffer,lineLength))
			{
				++j;
				if(1==j) // get name.
				{
					p=strchr(buffer,'\\');
					q=strchr(buffer,';');
					if(p&&q)
					{
						strncpy(pName,p+1,q-p-1);
					}
					p=q=NULL;
				}else if (2==j)	// get version
				{
					p=strchr(buffer,'=');
					strncpy(pVersion,p+2,VERSION_LEN);
					p=q=NULL;
				}
				//printf("buffer === %s \n",buffer);
			}
			fs.close();
		}
	}
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics