0

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?

demonking
  • 2,584
  • 5
  • 23
  • 28

2 Answers2

10

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.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 4
    I'd make age `unsigned` unless you need to process unborn students. –  Nov 14 '10 at 13:48
  • @demonking: If an answer solves your problem, you can accept it as correct using the tick to the left of the answer. This makes it easier to find for others with the same problem, and it rewards thoe that take the time to answer (consider this also for your other two questions). – Björn Pollex Nov 14 '10 at 13:53
  • It is [adviced](http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading#Bitwise_operators) to overload `>>` as `friend`. MVC at least will not even accept it, if it is not declared as such. – Arne Sep 02 '14 at 17:30
1

If you are on linux, you can mmap() the big file, and use data as it is in memory.

BЈовић
  • 62,405
  • 41
  • 173
  • 273