读取文本文件?
一文本文件中存有n条这样的记录:
struct Record
{
int id;
CString name;
CString other;
};
其中id,name,other都用逗号分开,记录与记录之间也用逗号分开,如何一个一个读去出来?
问题点数:100、回复次数:5Top
1 楼krh2001(边城浪子)回复于 2005-05-22 23:22:04 得分 40
FILE * f = fopen(filename", "r");
int id;
char name[128]; // 足够多大的缓冲
char other[128]; // 同上
while(fscanf(f, "%d,%s,%s,", &id, name, other)==3)
{
Record* p = new Record;
p->id = id;
p->name = name;
p->other = other;
m_listRecord.Add(p);
}
Top
2 楼krh2001(边城浪子)回复于 2005-05-22 23:35:55 得分 0
修正一下,经实测 fscanf一句 应改为:
while(fscanf(f, "%d,%[^,],%[^,],", &id, name, other)==3)
Top
3 楼fvan(RainVan)回复于 2005-05-22 23:48:50 得分 40
怎么最近问读写文本的人不少A?Top
4 楼fvan(RainVan)回复于 2005-05-22 23:53:35 得分 0
#include<fstream>//使用C++标准库
using namespace std;
struct Record
{
int id;
char name[256];
char other[256];//CString类本身有指针,读写麻烦,容易出错。固用数组
};
//写入文件
struct Record info;
ofstream outbal("test.bat",ios::out|ios::binary)//二进制打开,默认为文本
if(!outbal)
{
return false;//打开文件失败
}
outbal.write((char *)&info,sizeof(struct info));
outbal.close();
//读取文件
struct Record info;
ifstream inbal("test.bat",ios::in|ios::binary)//二进制打开,默认为文本
if(!inbal)
{
return false;//打开文件失败
}
inbal.read((char *)&info,sizeof(struct info));//读取到变量info中,如果文件有多组值,可用循环
inbal.close();
Top
5 楼lxcLinuxer(lxcLinuxer)回复于 2005-05-23 00:02:51 得分 20
创建一个新的locale,把';'加入到ctype_base::space中,如果你的字符串中有空格
的话,就把ctype_base::space加入到ctype_base::alpha中,然后把imbue到fstream中就
可以一个一个字段的读了。三个字段就是一个记录了。:)Top




