C++ MFC使用CStdioFile读写CSV文件
2020-08-06 14:00
1941 查看
逗号分隔值文件(csv文件)以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。
写csv文件:
需要注意:
- 写入中文时需进行示例中的设置。
- 换行只需要添加“\n”即可,不用添加“\r\n”。
[code]char currentPath[MAX_PATH]; memset(currentPath,0,sizeof(currentPath)); ::GetModuleFileNameA(NULL,currentPath,sizeof(currentPath)); strcpy (strrchr (currentPath, '\\')+1,"test.csv"); CString path = currentPath; CStdioFile mFile; if(!(mFile.Open( path, CFile::modeCreate|CFile::modeReadWrite))) { CString strTemp=_T("文件被占用,请关闭!"); AfxMessageBox(strTemp); return; } //设置区域为中文,不然无法写入中文 char* old_locale = _strdup(setlocale(LC_CTYPE,NULL)); setlocale(LC_CTYPE, ("chs")); mFile.SeekToBegin(); //找到文件开始位置 CString strWrite; strWrite = (_T("写入csv文件,1,2,3,4\n")); mFile.WriteString(strWrite); strWrite = (_T("写入csv文件,4,5,6,7\n")); mFile.WriteString(strWrite); setlocale(LC_CTYPE,old_locale); //还原区域 free(old_locale); mFile.Close(); //关闭文件
读取CSV文件:
[code]char* old_locale = _strdup(setlocale(LC_CTYPE,NULL)); setlocale(LC_CTYPE, ("chs")); char currentPath[MAX_PATH]; memset(currentPath,0,sizeof(currentPath)); ::GetModuleFileNameA(NULL,currentPath,sizeof(currentPath)); strcpy (strrchr (currentPath, '\\')+1,"test.csv"); CString path = currentPath; CStdioFile mFile; if(!(mFile.Open( path, CFile::modeRead))) { CString strTemp; strTemp.Format(_T("文件被占用,请关闭!"),path); AfxMessageBox(strTemp); return; } CString strArray[5]; CString strRead; while(file.ReadString(strRead)) { int count=0; int index = strRead.Find(_T(",")); while (index != -1 && count<5) { strArray[count++] = strRead.Left(index); strRead=strRead.Right(strRead.GetLength()-index-1); index = strRead.Find(_T(",")); } strArray[count++]=strRead; } setlocale(LC_CTYPE,old_locale); free(old_locale); mFile.Close();
相关文章推荐
- C++ MFC CFile 文件使用案例 读写文件 图像
- MFC中使用C++ 读写文件
- C++中通过MFC对ini初始化,配置文件的读写使用
- CFile和CStdioFile的文件读写使用方法
- 使用CStdioFile读写文件
- python3使用csv模块读写csv文件
- 想编一个局域网内的P2P文件传输软件,C++的,基于TCP协议,使用MFC需要建哪些类?
- C++读写CSV文件
- 【C++】读写CSV文件
- 使用opencsv文件读写CSV文件
- CFile和CStdioFile的文件读写使用方法
- MFC 文件的读写(其实还是c++的哪些东西)
- windows下VS2010中使用netcdf的C++接口实现.nc文件的读写
- CFile和CStdioFile的文件读写使用方法
- python使用csv模块读写csv文件
- mfc中如何使用cfile命令实现两个文件字符串交叉读写
- c++打开文件夹对话框GetOpenFileName 获取打开文件的filename(String类型)、使用Qt中QFileDialog打开、MFC中CFileDialog打开文件
- 使用CStdioFile读写文件
- CFile和CStdioFile的文件读写使用方法
- CFile和CStdioFile的文件读写使用方法