readout a big txt file
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 >&开发者_如何学Gogt; 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.
If you are on linux, you can mmap() the big file, and use data as it is in memory.
精彩评论