注册 登录
编程论坛 C++教室

怎么用MFC实现保存功能

gyp277953394 发布于 2011-04-18 10:24, 1358 次点击
我想编辑一个按钮让这个按钮能保存编辑框中的文字,现在知道能用CFile类,但是具体的代码看不明白
   HANDLE hFile = CreateFile(_T("D:\\MyFile.DAT"),
         GENERIC_WRITE, FILE_SHARE_READ,
         NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

   if (hFile == INVALID_HANDLE_VALUE)
      AfxMessageBox(_T("Couldn't create the file!"));
   else
   {
      // Attach a CFile object to the handle we have.
       CFile myFile(hFile);

      static const char sz[] = "Hockey is best!";

      // write string, without null-terminator
      myFile.Write(sz, lstrlen(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();
   }
请高手们指教
3 回复
#2
Lyone2011-04-19 11:02
   HANDLE hFile = CreateFile(_T("D:\\MyFile.DAT"),
         GENERIC_WRITE, FILE_SHARE_READ,
         NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

   if (hFile == INVALID_HANDLE_VALUE)
      AfxMessageBox(_T("Couldn't create the file!"));
   else
   {
      // Attach a CFile object to the handle we have.
       CFile myFile(hFile);

      static const char sz[] = "Hockey is best!";

      // write string, without null-terminator
      myFile.Write(sz, lstrlen(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();
   }

逐个百度出红色标注的程序功能,就可以明白这段代码在干什么了。我就是这样学习的。
#3
ljt2011-04-19 21:14
这个不是msdn上的么。先创建一个文件,然后用得到的句柄来给一个CFile对象赋值,在往里面写东西,最后关闭句柄。
今天我也用了这个,可是在evc下面有问题,那个CreateFile得到的句柄不能直接传递给CFile对象,不知道在Vc6下面行不行
#4
rjsp2011-04-20 08:15
那个CreateFile得到的句柄不能直接传递给CFile对象
--- 干嘛要用CFile?直接用 WriteFile,完毕后用 CloseHandle
1