读取文件到内存的问题

vicness 2008-11-15 08:56:42
各位大侠:
有个问题,就是我有一个文件,想把这个文件读取到内存中,并且把文件内容解析出来,文件中包含的数据结构类型为结构体类型,然后我想把文件中的数据放置到一个vector中,vector是一个结构体类型的。
谢谢各位!
...全文
111 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
nullah 2008-11-15
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 hqin6 的回复:]
C/C++ code




#include<fstream>

ifstream is("mytest.txt");

struct mystruct
{
int i;
int j;
string c;
};
mystruct ms;
vector<mystruct*> vm;

istream& operator>>(istream& is,mystruct& ms)
{
is>>ms.i>>ms.j>>ms.c;
return is;
}

while(is>>ms)
{
mystruct *ps = new mystruct;
vm.push_back(ps);
}

最后记得释放!!!!
[/Quote]

UP
太乙 2008-11-15
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 vicness 的回复:]
readline函数如何去用啊?
[/Quote]

lz说的是getline吧??

vicness 2008-11-15
  • 打赏
  • 举报
回复
readline函数如何去用啊?
太乙 2008-11-15
  • 打赏
  • 举报
回复





#include<fstream>

ifstream is("mytest.txt");

struct mystruct
{
int i;
int j;
string c;
};
mystruct ms;
vector<mystruct*> vm;

istream& operator>>(istream& is,mystruct& ms)
{
is>>ms.i>>ms.j>>ms.c;
return is;
}

while(is>>ms)
{
mystruct *ps = new mystruct;
vm.push_back(ps);
}

最后记得释放!!!!





太乙 2008-11-15
  • 打赏
  • 举报
回复


#include<fstream>

ifstream is("mytest.txt");

struct mystruct
{
int i;
int j;
string c;
};
mystruct ms;
vector<mystruct> vm;
while(is>>ms.i>>ms.j>>ms.c)
{
vm.push_back(ms);
}

就是上面的意思

不过可以改进:

第一:重载struct的>>操作符号
第二:vector 存放指针,而不是对象!


vicness 2008-11-15
  • 打赏
  • 举报
回复
晕,能不能说的详细下?
dqlihb 2008-11-15
  • 打赏
  • 举报
回复
用流文件
liecs 2008-11-15
  • 打赏
  • 举报
回复
fopen,fread,fclose

open, read, close
vicness 2008-11-15
  • 打赏
  • 举报
回复
如何做啊?
之前没处理过这块
  • 打赏
  • 举报
回复

完全可以啊!有什么问题吗?
wudeshou82666 2008-11-15
  • 打赏
  • 举报
回复
ifstream is("mytest.txt");
这里最好加个判断
if(!is)
{
printf("...............\n");
return 0;
}

getline()就是没次读取一行,遇到换行符结束.
是一个函数模板

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧