MFC判断文件是否存在,不存在则创建+CSV文件操作
CString strFileName;
SYSTEMTIME sysLocaltime;
GetLocalTime(&sysLocaltime);
strFileName.Format(_T("D:\\TestData\\%04i-%02i-%02i"), sysLocaltime.wYear
, sysLocaltime.wMonth, sysLocaltime.wDay);
//创建目录
SHCreateDirectoryExW(NULL, strFileName, NULL);
strFileName += _T("\\data.csv");
int sign(0);
try
{
CFileFind finder;
//判断文件是否存在,存在返回true,不存在返回false
BOOL bWorking = (bool)finder.FindFile(strFileName);
if (!bWorking)
{
//目录不存在
sign = 1;
}
//创建文件
CFile LPFile(strFileName, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate);
LPFile.SeekToEnd();//到文件尾
CStringA strbuf;
if (sign == 1)//目录不存在,创建CSV文件时加入表头内容
{
strbuf.Format("登记日期,");
strbuf.AppendFormat("姓名,");
strbuf.AppendFormat("性别,");
strbuf.AppendFormat("年龄");
strbuf += ",\r\n";
strbuf.AppendFormat("%04i-%02i-%02i %02i:%02i:%02i,", sysLocaltime.wYear, sysLocaltime.wMonth
, sysLocaltime.wDay, sysLocaltime.wHour, sysLocaltime.wMinute, sysLocaltime.wSecond);
}
else//目录存在,直接在CSV文件中写入内容
{
strbuf.Format("%04i-%02i-%02i %02i:%02i:%02i,", sysLocaltime.wYear, sysLocaltime.wMonth
, sysLocaltime.wDay, sysLocaltime.wHour, sysLocaltime.wMinute, sysLocaltime.wSecond);
}
strbuf += "小李,";
strbuf += "女,";
strbuf += "26";
strbuf += ",\r\n";//换行
LPFile.Write(strbuf.GetString(), strbuf.GetLength());//写入内容
LPFile.Close();
}
catch (CException* e)
{
TCHAR szCause[255];
e->GetErrorMessage(szCause, 255);
}