10 fseek(pFile,0,SEEK_SET); //读取数据前,需要将指针再指回起始位置
11 fread(pbuf,1,len,pFile);
12 pbuf [len]='\0';
13 fclose(pFile);
14 MessageBox(pbuf);
15 }
12.2.3二进制文件和文本文件
字太多,有点啰嗦,不写了,慢慢体会。
12.3C++对文件操作的支持
01 void CFileView::OnFileWrite()//写入
02 {
03 ofstream ofs("3.txt");
04 ofs.write("www.colsir.com",strlen("www.colsir.com"));
05 ofs.close();
06 }
07 void CFileView::OnFileRead() //读取
08 {
09 // TODO: Add your command handler code here
10 ifstream ifs("3.txt");
11 char buf[100];
12 memset(buf,0,100);
13 ifs.read(buf,100);
14 ifs.close();
15 MessageBox(buf);
16 }
12.4Win32 API对文件操作的支持
01 void CFileView::OnFileWrite()//写入
02 {
03 HANDLE hFile;
04 hFile=CreateFile("4.txt",GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
05 DWORD dwWrites;
06 WriteFile(hFile,"www.colsir.com",strlen("www.colsir.com"),&dwWrites,NULL);
07 CloseHandle(hFile);
08 }
09 void CFileView::OnFileRead()//读取
10 {
11 // TODO: Add your command handler code here
12 HANDLE hFile;
13 hFile=CreateFile("4.txt",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
14 char buf[100];
15 DWORD dwWrites;
16 ReadFile(hFile,buf,100,&dwWrites,NULL);
17 buf[dwWrites]=0;
18 CloseHandle(hFile);
19 MessageBox(buf);
20 }
12.5MFC对文件操作的支持
MFC中提供的支持文件操作的基类是:CFile,该类提供了没有缓存的二进制格式的磁盘文件输入输出功能,通过其派生类能够间接的支持文本文件和内存文件。
利用MFC的CFile类实现文件写入操作:
1 void CFileView::OnFileWrite()
2 {
3 CFile file("5.txt",CFile::modeCreate|CFile::modeWrite);
4 file.Write("www.colsir.com",strlen("www.colsir.com"));
5 file.Close();
6 }
利用MFC的CFile类实现文件读取操作:
01 void CFileView::OnFileRead()
02 {
03 CFile file("5.txt",CFile::modeRead);
04 char *pBuf;
责任编辑:小草