CListCtrl控件删除某行数据,对应txt文件删除对应的数据

 CStdioFile pFile;
POSITION pos = m_CLiseCtrl.GetFirstSelectedItemPosition();//获取鼠标当前位置
if (NULL == pos)
{
MessageBox(L"不能删除空行!");
}
int nItem = m_CLiseCtrl.GetNextSelectedItem(pos);     

m_CLiseCtrl.DeleteItem(nItem);// 删除当前内容
int index = m_CLiseCtrl.GetHeaderCtrl()->GetItemCount();        //获取列数
CString listval[4];


//遍历每一列
listval[0] = m_CLiseCtrl.GetItemText(nItem, 0);
char* old_locale = _strdup(setlocale(LC_CTYPE, NULL));
setlocale(LC_CTYPE, "chs");//设定


// TODO:  在此添加专用代码和/或调用基类


//GetDlgItem(IDC_BUTTON2)->EnableWindow(FALSE);
int iRows = 0;
if (!pFile.Open(_T("DepartMent.txt"), CFile::modeNoTruncate | CFile::modeReadWrite))
{
return;
}
else
{
pFile.SeekToBegin();
CString pStrText;
DWORD dwPos = 0;
while (pFile.ReadString(pStrText)) //读取文件一行
{
int curPos = 0;


for (int iCols = 0; iCols < 4; iCols++)      //遍历列
{
if (curPos == -1)
{
break;
}
if (iCols == 0)
{
CString resToken = pStrText.Tokenize(_T("|"), curPos); //"|"分隔字符串
if (resToken == listval[0])
{
dwPos = (DWORD)pFile.GetPosition() - (_tcslen(listval[0]) + _tcslen(_T("\r\n")));
}
}
}
iRows++;
}
}
pFile.Close();


//删除txt文件里对应的内容
CStdioFile pFiles;
CString strFileName = _T("DepartMentNew.txt");
int nCount = 0;
CString Temp;


if (!pFiles.Open(strFileName, CFile::typeText | CFile::modeCreate | CFile::modeReadWrite |   CFile::modeNoTruncate))
{
return;
}
for (int i = 0; i < m_CLiseCtrl.GetItemCount(); i++)
{
//遍历每一列数据
CString listval[4];
listval[0] = m_CLiseCtrl.GetItemText(i, 0);
listval[1] = m_CLiseCtrl.GetItemText(i, 1);
listval[2] = m_CLiseCtrl.GetItemText(i, 2);
listval[3] = m_CLiseCtrl.GetItemText(i, 3);


Temp = listval[0] + "|" + listval[1] + "|" + listval[2] + "|" + listval[3] + _T("\n");
pFiles.WriteString(Temp);


}
setlocale(LC_CTYPE, old_locale);
free(old_locale);//还原区域设定
pFiles.Close();
CFile::Remove(_T("DepartMent.txt"));                //删除原来的文件
CFile::Rename(strFileName, _T("DepartMent.txt")); //将新文件命名为原来的文件

你可能感兴趣的:(c++)