天天看點

VC++檔案操作

try
  {
    CString strText;
    strText.Format("%d,%s%s", iFacIndex, strTime, strValue);
    if (GetFileAttributes("data.txt") == INVALID_FILE_ATTRIBUTES)
    {
      HANDLE hOpenFile = CreateFileA(_T("data.txt"),GENERIC_WRITE,
                                FILE_SHARE_READ|FILE_SHARE_WRITE,
        NULL,CREATE_ALWAYS/*|OPEN_EXISTING*/,FILE_ATTRIBUTE_NORMAL,NULL);
      if (hOpenFile != INVALID_HANDLE_VALUE)
      {
        DWORD dwBytesWritten;
        WriteFile(hOpenFile, strText.GetBuffer(), strText.GetLength(), 
                                          &dwBytesWritten, NULL);
        CloseHandle((void *)hOpenFile);
      }
    }
    else
    {
      CFile file;
      if (file.Open("data.txt",CFile::modeCreate|CFile::shareDenyNone|CFile::modeWrite
                                      /*|CFile::typeText*/))
      {
        file.Write(strText.GetBuffer(), strText.GetLength());
        file.Close();
      }
    }
  }
  catch (CMemoryException* e)
  {
    TCHAR szBuff[MAX_PATH+1]={0};
    e->GetErrorMessage(szBuff, MAX_PATH);
    AfxMessageBox(szBuff);
  }
  catch (CFileException* e)
  {
    TCHAR szBuff[MAX_PATH+1]={0};
    e->GetErrorMessage(szBuff, MAX_PATH);
    AfxMessageBox(szBuff);
  }
  catch (CException* e)
  {
    TCHAR szBuff[MAX_PATH+1]={0};
    e->GetErrorMessage(szBuff, MAX_PATH);
    AfxMessageBox(szBuff);
  }      

說明:

1.如果檔案不存在,CreateFile指定OPEN_EXISTING标志将導緻調用失敗;

繼續閱讀