读出一个大txt文件 [英] readout a big txt file

查看:126
本文介绍了读出一个大txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有另一种方式读出大文件

  Hans // name 

Bachelor // study_path

WS10_11 //学期

22 //年龄

而不是这样:

  fout>名称; // string 

fout>> study_path; // string

fout>>学期; // string

fout>>年龄;当我的文件变成20多行时,我应该使20多个fouts?/ / int



有另一种方法吗?

解决方案

每个人的数据:

  class Person {
public:
std :: string name;
std :: string study_path;
std :: string semester;
unsigned int age;
};

然后您可以为该类定义流提取运算符:

  std :: istream& operator>>(std :: istream& stream,Person& person){
stream>> person.name>> person.study_path>> person.semester>>人士;
return stream;
}

然后你可以读取整个文件:

  std :: ifstream file(datafile.txt); 
std :: vector< Person>数据;
std :: copy(std :: istream_iterator< Person>(file),std :: istream_iterator< Person>(),
std :: back_inserter

这将读取整个文件,并将所有提取的记录存储在 。如果您知道您将提前读取的记录数,可以在读取文件之前调用 data.reserve(number_of_records)。因此,向量将具有足够的存储器来存储所有记录而不重新分配,如果文件较大,则可能加速加载。


i want to know, if there is another way to readout a big file

Hans //name

Bachelor // study_path

WS10_11 //semester

22 // age 

and not like this:

fout >> name; //string

fout >> study_path; //string

fout >> Semester ; //string

fout >> age; //int

when my file turns to more than 20 line's i should make 20+ fouts?

Is there another way?

解决方案

You could define a class to hold the data for each person:

class Person {
public:
    std::string name;
    std::string study_path;
    std::string semester;
    unsigned int age;
};

Then you can define a stream extraction operator for that class:

std::istream & operator>>(std::istream & stream, Person & person) {
    stream >> person.name >> person.study_path >> person.semester >> person.age;
    return stream;
}

And then you can just read the entire file like that:

std::ifstream file("datafile.txt");
std::vector<Person> data;
std::copy(std::istream_iterator<Person>(file), std::istream_iterator<Person>(),
          std::back_inserter(data));

This will read the entire file and store all the extracted records in a vector. If you know the number of records you will read in advance, you can call data.reserve(number_of_records) before reading the file. Thus, the vector will have enough memory to store all records without reallocation, which might potentially speed up the loading if the file is large.

这篇关于读出一个大txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆