VC++文件操作

来源:互联网 发布:神武2mac版能玩吗 编辑:程序博客网 时间:2024/06/07 19:41
 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标志将导致调用失败;

2.CFile不支持文本格式打开,只能在继承类中使用,Open中指定typeText标志将导致程序崩溃;

3.代码中判断文件是否存在功能有重复,只是为了展示文件用法需要。

0 0
原创粉丝点击