文件操作系列之四——(CFile类的文件操作)

CFile提供的是一种无缓冲的二进制文件输入输出服务,他还可以通过他的派生类来支持文本文件和内存信息的传输。

你可以使用CFILE的和他的派生类来操作硬盘的标准I / O流操作,你还可以使用ofstream或其他微软的iostream类格式化文本文件之后在传输磁盘文件。

通常,一个文件通过CFILE的构造函数自动的打开,通过他的析构函数自动的销毁关闭。而他的静态成员函数可以让你在不打开文件的情况下就可以访问文件的状态。

下面直接上代码说明:

读文件:

cout<<"Pleast input the file name you want to Write:/n"; char filename[50]; cin>>filename; WCHAR wschar[50]; MultiByteToWideChar( CP_ACP, 0, filename, strlen(filename)+1, wschar, sizeof(wschar)/sizeof(wschar[0]) ); //HANDLE hFile = CreateFile(wschar, // GENERIC_READ, FILE_SHARE_READ, // NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //使用构造函数 //if (hFile == INVALID_HANDLE_VALUE) //{ // cout<<"Couldn't create the file!/n"; // return; //} //else //{ // // Attach a CFile object to the handle we have. // CFile myFile(hFile); // // read string // char pbufRead[100]; // myFile.Read(pbufRead, sizeof(pbufRead)); // cout<<pbufRead; // // We can call Close() explicitly, but the destructor would have // // also closed the file for us. Note that there's no need to // // call the CloseHandle() on the handle returned by the API because // // MFC will close it for us. // myFile.Close(); //} CFile f; CFileException e; if(!f.Open(wschar, CFile::modeRead, &e)) //使用Open函数 { TRACE(_T("File could not be opened %d/n"), e.m_cause); } char pbufRead[100]; memset(pbufRead, 0, 100); DWORD dwRead; do { dwRead = f.Read(pbufRead, sizeof(pbufRead)); for (size_t i = 0; i < dwRead;++i) { cout<<pbufRead[i]; } } while (dwRead > 0); f.Close();

写文件:

char filename[50]; cout<<"Pleast input the file name you want to Read:/n"; cin>>filename; WCHAR wschar[50]; MultiByteToWideChar( CP_ACP, 0, filename, strlen(filename)+1, wschar, sizeof(wschar)/sizeof(wschar[0]) ); HANDLE hFile = CreateFile(wschar, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { cout<<"Couldn't create the file!/n"; return; } else { // Attach a CFile object to the handle we have. CFile myFile(hFile); static const char sz[] = "I love CFile!"; // write string myFile.Write(sz, sizeof(sz)); // We can call Close() explicitly, but the destructor would have // also closed the file for us. Note that there's no need to // call the CloseHandle() on the handle returned by the API because // MFC will close it for us. myFile.Close(); }

代码上附有注释说明,对于其详细说明,可以参考MSDN上的说明。

除了代码上所说的读写之外,我们还可以获取文件的名字,标题,路径等属性:

         可以发现,使用CFile使文件操作进行的更加方便,我们也不用太担心像使用Run-Time Library函数的危险性。不过,缺点也很明显,依赖于MFC库,

         而且,灵活性明显不如前面所说方法高。不过有利就有弊,具体使用哪个,还需我们自己权衡。

         附,本系列示例代码 ,该代码在VS2008+XPsp3下测试通过。

你可能感兴趣的:(object,File,null,mfc,iostream,destructor)