mfc怎么按行读取文件内容分割显示到listctrl控件内
时间: 2024-02-12 07:08:48 浏览: 28
在MFC中使用CListCtrl控件按行读取文件内容并分割显示到控件中,可以参考下面的代码示例:
```cpp
// 声明控件变量
CListCtrl m_listCtrl;
// 创建控件
m_listCtrl.Create(WS_VISIBLE | WS_CHILD | LVS_REPORT, CRect(10, 10, 300, 200), this, IDC_LIST_CTRL);
// 添加列标题
m_listCtrl.InsertColumn(0, _T("Name"), LVCFMT_LEFT, 100);
m_listCtrl.InsertColumn(1, _T("Age"), LVCFMT_LEFT, 50);
m_listCtrl.InsertColumn(2, _T("Gender"), LVCFMT_LEFT, 50);
// 打开文件
CStdioFile file;
if (file.Open(_T("file.txt"), CFile::modeRead)) {
CString strLine;
while (file.ReadString(strLine)) {
// 分割每一行数据
CString strName, strAge, strGender;
int iPos1 = strLine.Find(_T(","));
int iPos2 = strLine.Find(_T(","), iPos1 + 1);
strName = strLine.Left(iPos1);
strAge = strLine.Mid(iPos1 + 1, iPos2 - iPos1 - 1);
strGender = strLine.Right(strLine.GetLength() - iPos2 - 1);
// 在ListCtrl控件中添加每一行数据
int iItem = m_listCtrl.GetItemCount();
m_listCtrl.InsertItem(iItem, strName);
m_listCtrl.SetItemText(iItem, 1, strAge);
m_listCtrl.SetItemText(iItem, 2, strGender);
}
file.Close();
}
```
在上面的代码中,我们使用CStdioFile类打开文件并逐行读取文件内容,然后使用Find()方法分割每一行数据。在分割后,我们使用InsertItem()方法将每一行数据添加到ListCtrl控件中,并使用SetItemText()方法设置每一列的文本内容。
这个代码示例可以按行读取文件内容并将其分割显示到CListCtrl控件中,希望能对您有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)